Chapter 6-dictionary and chapter 6 Dictionary
1 # ***** create multiple dictionaries and store them in a list to print all dictionaries. *** #2 pet1 = {3 'type': 'dog ', 'ower ': 'Peter '} 4 pet2 = {5 'type': 'cat', 'ower': 'lili'} 6 pet3 = {7 'type': 'rabbit ', 'ower': 'heli'} # create a dictionary using curly brackets 8 pets = [pet1, pet2, pet3] # When multiple dictionaries are saved in a list, the brackets 9 for pet in pets: 10 print (pet) # print all dictionaries 11 # ******** the dictionary key value contains multiple elements ****** #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) # line feed 19 print (places) # note the difference between this sentence and the following two sentences. This sentence is printed with brackets 20 for place in places: 21 print ("\ t" + place) # "\ t" space, which is printed out without brackets and automatically wrap 22 # *** create a dictionary in the dictionary *** #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)
The running result is as follows:
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