字典_嵌套

有时需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套

包含字典的列表

player1 = {'color': 'green', 'points': 5}
player2 = {'color': 'yellow', 'points': 10}
player3 = {'color': 'red', 'points': 15}

players = [player1, player2, player3]

for player in players:
    print(player)

out:
{'points': 5, 'color': 'green'}
{'points': 10, 'color': 'yellow'}
{'points': 15, 'color': 'red'}

创建一个用于存储玩家的空列表,不断添加append()可以使可以的

players = []

for player_number in range(30):
    new_player = {'color': 'green', 'points': 5, 'speed': 'slow'}
    players.append(new_player)

for player in players[:5]:
    print(player)
print("...")

print("Total number of players: " + str(len(players)))

out:
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
...
Total number of players: 30

字典中存储列表

描述字典可以用列表存储信息

person_languages = {
    'A': ['python', 'ruby'],
    'B': ['c'],
    'C': ['ruby', 'go'],
    'D': ['python', 'java'],
    }

for name ,languages in person_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title())

out:
A's favorite languages are:
	Python
	Ruby

B's favorite languages are:
	C

C's favorite languages are:
	Ruby
	Go

D's favorite languages are:
	Python
	Java

字典中包含字典

对于多个用户对应各自不同的信息,可以使用字典集合嵌套在字典中

game_name = {
    'wanjia1': {
        'first': 'albet',
        'last': 'einstein',
        'location': 'wuxi',
        },
    'wanjia2': {
        'first': 'saeq',
        'last': 'curie',
        'location': 'paris',
        },
    }
for name,game_name_info in game_name.items():
    print("\n 游戏名: " + name)
    full_name = game_name_info['first'] + " " + game_name_info['last']
    location = game_name_info['location']

    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())

out:
 游戏名: wanjia1
	Full name: Albet Einstein
	Location: Wuxi

 游戏名: wanjia2
	Full name: Saeq Curie
	Location: Paris

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值