当前位置: 移动技术网 > IT编程>脚本编程>Python > 字典的学习3——嵌套——Python编程从入门到实践

字典的学习3——嵌套——Python编程从入门到实践

2019年06月22日  | 移动技术网IT编程  | 我要评论

党报回应奥巴马指责,男后妤灵,9c8968航班

嵌套 ?

一系列字典存储在列表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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网