字典的value可以是任何python对象。操作非常灵活。
字典数据结构中存在的基本操作 :
- 访问字典
- 添加key-value对
- 修改字典value
- 删除key-value
- 遍历字典
删除key-value
dict = {"one":3, "two":"hello,world", "three":23.8, "four":True};
print "原来的字典序列:",dict;
del dict["one"];
print "删除后的字典序列:", dict;
输出的结果是:
原来的字典序列: {'four': True, 'three': 23.8, 'two': 'hello,world', 'one': 3}
删除后的字典序列: {'four': True, 'three': 23.8, 'two': 'hello,world'}
遍历字典
遍历key-value对
dict = {"one":3, "two":"hello,world", "three":23.8, "four":True};
for key,value in dict.items():
print "key=",key,
print "value=", value;
输出的结果是:
key= four value= True
key= three value= 23.8
key= two value= hello,world
key= one value= 3
遍历key
dict = {"one":3, "two":"hello,world", "three":23.8, "four":True};
for key in dict.keys():
print "key=",key;
输出的结果是:
key= four
key= three
key= two
key= one
遍历value
dict = {"one":3, "two":"hello,world", "three":23.8, "four":True};
for value in dict.values():
print "value=",value;
输出的结果是:
value= True
value= 23.8
value= hello,world
value= 3
网友评论