第六章——字典,第六章字典
1 #*****建立多字典存入一個列表中列印所有字典***# 2 pet1={ 3 'type':'dog', 'ower':'peter'} 4 pet2={ 5 'type':'cat','ower':'lili'} 6 pet3={ 7 'type':'rabbit','ower':'heli'} #建立字典使用花括弧 8 pets=[pet1,pet2,pet3] #將多個字典存放入一個列表中時是中括弧 9 for pet in pets:10 print(pet) #列印所有的字典11 #*******字典索引值中值含有多個元素******#12 favorate_place={13 'peter':['a','b','c'],14 'lili':['c','d','e'],15 'helo':['f','g','h']16 }17 for name,places in favorate_place.items():18 print("\n"+name)#換行19 print(places)#注意這句與下面兩句的區別,此句列印出來有中括弧20 for place in places:21 print("\t"+place)#"\t"空格,這種列印出來沒有中括弧,並且自動換行22 #***字典中建立字典****#23 cities={24 "Beijing":{25 'country':'China',26 'population':'13',27 'fact':'a'28 },29 "Haerbin":{30 'country':'China',31 'population':'13',32 'fact':'b'33 },34 "Changsha":{35 'country':'China',36 'population':'13',37 'fact':'b'38 }39 }40 for city,infos in cities.items():41 print(city)42 print(infos)
運行結果如下:
D:\Python\python.exe F:/python-example/6_4.py{'type': 'dog', 'ower': 'peter'}{'type': 'cat', 'ower': 'lili'}{'type': 'rabbit', 'ower': 'heli'}peter['a', 'b', 'c'] a b clili['c', 'd', 'e'] c d ehelo['f', 'g', 'h'] f g hBeijing{'country': 'China', 'population': '13', 'fact': 'a'}Haerbin{'country': 'China', 'population': '13', 'fact': 'b'}Changsha{'country': 'China', 'population': '13', 'fact': 'b'}Process finished with exit code 0