1. 程式人生 > >python -dict

python -dict

strong print zip 遍歷 添加 ron app term int

#字典的添加、刪除、修改操作
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
dict["w"] = "watermelon" #添加
del(dict["a"]) #刪除
dict["g"] = "grapefruit"
print dict.pop("b")
print dictdict.clear() #清空
print dict
#字典的遍歷


dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
  print "dict[%s] =" % k,dict[k]
#字典items()的使用
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
每個元素是一個key和value組成的元組,以列表的方式輸出print dict.items()
#調用items()實現字典的遍歷

dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k, v) in dict.items():
  print "dict[%s] =" % k, v
#調用iteritems()實現字典的遍歷
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
print dict.iteritems()
for k, v in dict.iteritems():
  print "dict[%s] =" % k, v
for (k, v) in zip(dict.iterkeys(), dict.itervalues()):
  print "dict[%s] =" % k, v

python -dict