dict = {1 : "apple", 2 : "banana", 3 : "grape", 4 : "orange"} dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
# 字典的元素 print dict.items() >>> [('a', 'apple'), ('b', 'banana'), ('o', 'orange'), ('g', 'grape')] print dict.keys() >>> ['a', 'b', 'o', 'g'] print dict.values() >>> ['apple', 'banana', 'orange', 'grape']
# 添加删除元素 dict["w"] = "water" del dict['w']
dict.pop("b") dict.clear()
# 字典遍历 for k in dict: print "dict[%s] =" % k,dict[k]
for (k, v) in dict.items(): print "dict[%s] =" % k, v
#字典更新 dict = {"a" : "apple", "b" : "banana"} print dict >>> {'a': 'apple', 'b': 'banana'} dict2 = {"c" : "grape", "d" : "orange"} print dict2 >>> {'c': 'grape', 'd': 'orange'} dict.update(dict2) print dict >>> {'a': 'apple', 'c': 'grape', 'b': 'banana', 'd': 'orange'}
# 字典排序 # 按照key排序 print sorted(dict.items(), key=lambda d: d[0]) # 按照value排序 print sorted(dict.items(), key=lambda d: d[1])
|