嵌套

1.字典列表

# create a list to store all aliens
aliens = []
# create initial 30 green aliens
for alien_number in range(0, 30):
    new_alien = {
        'color': 'green',
        'points': 5,
        'speed': 'slow',

    }
    aliens.append(new_alien)
# level up! some of them has upgraded now!
for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['points'] = 10
        alien['speed'] = 'medium'
# show first 5 aliens
for alien in aliens[0:5]:
    print(alien)

⚠️:列表中添加元素(字典)

# create a list to store all aliens
aliens = []
and
aliens.append(new_alien)

2.在字典中储存列表

# store the information of pizzas
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese']
}
# describe the pizza you just made
print('You ordered a ' + pizza['crust'] + '-crust pizza with the following toppings')
# list all the toppings
for topping in pizza['toppings']:
    print("\t" + topping)

⚠️:遍历列表时,需指定是字典中的列表

for topping in pizza['toppings']:

3.字典中的字典

# define a dictionary with two sub-dictionaries as keys
users = {
    'HalO': {
        'first': 'Bing',
        'last': 'Lucas',
        'location': 'China',
    },
    '404': {
        'first': 'Qing',
        'last': 'Linnea',
        'location': 'England',
    },
}
# try to get the value inside the dictionary
for user_name, user_info in users.items():
    print("\nUsername: " + user_name)
    full_name = user_info['last'] + " " + user_info['first']
    location = user_info['location']
    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值