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 c lili ['c', 'd', 'e'] c d e helo ['f', 'g', 'h'] f g h Beijing {'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