嵌套 ? 一系列字典存儲在列表or列表作為值存儲在字典or字典中套字典 1. 字典列表 這樣手動一個一個輸入太費勁,讓其自動生成多個: 但此時生成的數量是很多了,可都具有一樣的特征,怎麼辦呢? 通過切片修改部分外星人的特征,就可生成具有不同特征的外星人。 2. 在字典中存儲列表 多個鍵值對時: 運行 ...
嵌套 ?
一系列字典存儲在列表or列表作為值存儲在字典or字典中套字典
1. 字典列表
alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 15} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alien)
這樣手動一個一個輸入太費勁,讓其自動生成多個:
aliens = [] # 生成30個 for alien_number in range(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) # 顯示前5個 for alien in aliens[:5]: print(alien)
但此時生成的數量是很多了,可都具有一樣的特征,怎麼辦呢?
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['point'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['point'] = 15
通過切片修改部分外星人的特征,就可生成具有不同特征的外星人。
2. 在字典中存儲列表
# 存儲披薩的信息 pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'], } # 概述所點的披薩 print("You ordered a " + pizza['crust'] + "-crust pizza with the following toppings:") for topping in pizza['toppings']: print(topping)
多個鍵值對時:
favorite_languages = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } for name, languages in favorite_languages.items(): print("\n" + name.title() + "'s favorite languages are: ") for language in languages: print("\t" + language.title())
運行結果:
Jen's favorite languages are: Python Ruby Sarah's favorite languages are: C Edward's favorite languages are: Ruby Go Phil's favorite languages are: Python Haskell
但有的鍵只對應一個值,用are表示就有點不妥,可以對此作進一步改進:
for name, languages in favorite_languages.items(): if len(languages) == 1: print("\n" + name.title() + "'s favorite languages is " + languages[0].title() + ".") # 列印出一個鍵對應一個值的情況 else: print("\n" + name.title() + "'s favorite languages are: ") for language in languages: print("\t" + language.title())
3. 字典中存儲字典
# 存儲兩個用戶各自的一些信息 users = { 'mary': { 'first': 'albert', 'last': 'mary', 'location': 'princeton', }, 'bary': { 'first': 'maria', 'last': 'bary', 'location': 'paris', } } for username, user_info in users.items(): full_name = user_info['first'] + ' ' + user_info['last'] location = user_info['location'] print("\nUsername: " + username) print('\tFull name: ' + full_name.title()) print('\tLocation: ' + location.title())
運行結果:
Username: mary
Full name: Albert Mary
Location: Princeton
Username: bary
Full name: Maria Bary
Location: Paris