Python 字典嵌套

字典嵌套

  • 含义:将一系列字典存储在列表中,或将列表作为值存储在字典中
  • 在列表中嵌套字典、在字典中嵌套列表、在字典中嵌套字典

字典列表

  • 创建多个字典,将字典存放在列表中
  • 使用range()自动生成多个字典
  • 使用for循环及if语句修改创建的多个字典
# 案例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)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
# 案例2: 使用range()自动创建多个字典,最后存放到列表中
# 创建一个用于存储的空列表
aliens = []
# 创建30个具体的字典
for alien in range(30):
    new_alien = {'color': 'green','points': '5','speed': 'slow'}
    aliens.append(new_alien)
# 显示前五个字典
for alien in aliens[:5]:
    print(alien)
print(".....")
# 显示创建了多少个字典
print("Total number of aliens: " + str(len(aliens)))
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
.....
Total number of aliens: 30
# 案例3:修改其中创建的字典
# 创建一个用于存储的空列表
aliens = []
# 创建30个具体的字典
for alien_number in range(0,30):
    new_alien = {'color': 'green','points': '5','speed': 'slow'}
    aliens.append(new_alien)
# 修改前3个字典
for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['points'] = 10
        alien['speed'] = 'medium'
# 显示前5个字典
for alien in aliens[:5]:
    print(alien)
print(".....")

{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
.....

在字典中存储列表

  • 将列表存储到字典中
  • 使用字典名和键来访问值
  • 列表和字典的嵌套层次不应该太多
# 案例1:
# 存储所点比萨的信息
pizza = {
    'curst' : 'thick',
    'toppings': ['mushrooms','extra cheese'],
}
# 概述所点的比萨
print("You ordered a " + pizza['curst'] + "-crust pizza" + 
      " with the following toppings:")
for topping in pizza['toppings']:
    print("\t" + topping)
You ordered a thick-crust pizza with the following toppings:
	mushrooms
	extra cheese
# 案例2:
# 字典中嵌套列表,用两个for循环,第一个for循环遍历字典,第二个for循环遍历列表
favorite_languages = {
    'jen': ['python','ruby'],
    'sarah': ['c'],
    'edward': ['ruby','go'],
    'phil': ['python','haskell'],
}
# 遍历字典
for name,languages in favorite_languages.items():
    #判断字典的值有几个
    if len(languages) > 1:
        print("\n" + name.title() + " 's favorite language are:")
        # 字典的值是列表时,for循环遍历列表
        for language in languages:
                print("\t" + language.title())
    else:
        print("\n" + name.title() + " 's favorite language is:")
        print("\t" + languages[0].title())
Jen 's favorite language are:
	Python
	Ruby

Sarah 's favorite language is:
	C

Edward 's favorite language are:
	Ruby
	Go

Phil 's favorite language are:
	Python
	Haskell

在字典中存储字典

# 首先定义了一个名为 users 的字典,其中包含两个键:用户名 'aeinstein' 和 'mcurie' ;
# 与每个键相关联的值都是一个字典,其中包含用户的名、姓和居住地,我们遍历字典 users ,
# 让 Python 依次将每个键存储在变量 username 中,并依次将与当前键相关联的字典存储在变量
# user_info 中。在主循环内部,我们将用户名打印出来。
# 我们开始访问内部的字典。变量 user_info 包含用户信息字典,而该字典包含三个键: 
# 'first' 、 'last' 和 'location' ;对于每位用户,我们都使用这些键来
# 生成整洁的姓名和居住地,然后打印有关用户的简要信息
users = {
    'asinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
    },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
    },
}
for username,user_info in users.items():
    print("\nUsername: " + username.title())
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']
    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())
Username: Asinstein
	Full name: Albert Einstein
	Location: Princeton

Username: Mcurie
	Full name: Marie Curie
	Location: Paris

练习

# 1.人
#使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。
#该字典应包含键 first_name 、 last_name 、 age 和 city 。将存储在该字典中
#的每项信息都打印出来。
#创建两个表示人的字典,然后将这三个字典都存储在一个名为 people 的列表中。遍历这个列表
#将其中每个人的所有信息都打印出来
people1 = {
    'first_name': 'li',
    'last_name': 'si',
    'age': '23',
    'city': 'Beijing'
    }
people2 = {
    'first_name': 'zhang',
    'last_name': 'san',
    'age': '24',
    'city': 'dalian'
    }
people3 = {
    'first_name': 'wang',
    'last_name': 'badan',
    'age': '20',
    'city': 'shanghai'
    }
peoples = [people1,people2,people3]
for people in peoples:
    name = people['first_name'].title() + " " + people['last_name'].title()
    age = str(people['age'])
    city = people['city'].title()
    print(name + ", of " + city  + ",is " + age + " years old.")
Li Si, of Beijing,is 23 years old.
Zhang San, of Dalian,is 24 years old.
Wang Badan, of Shanghai,is 20 years old.
# 2.宠物
#创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,
#包含宠物的类型及其主人的名字。将这些字典存储在一个名为 pets
#的列表中,再遍历该列表,并将宠物的所有信息都打印出来
# Make an empty list to store the pets in.
pets = []

# Make individual pets, and store each one in the list.
pet = {
    'animal type': 'python',
    'name': 'john',
    'owner': 'guido',
    'weight': 43,
    'eats': 'bugs',
}
pets.append(pet)

pet = {
    'animal type': 'chicken',
    'name': 'clarence',
    'owner': 'tiffany',
    'weight': 2,
    'eats': 'seeds',
}
pets.append(pet)

pet = {
    'animal type': 'dog',
    'name': 'peso',
    'owner': 'eric',
    'weight': 37,
    'eats': 'shoes',
}
pets.append(pet)

# Display information about each pet.
for pet in pets:
    print("\nHere's what I know about " + pet['name'].title() + ":")
    for key, value in pet.items():
        print("\t" + key + ": " + str(value))
Here's what I know about John:
	animal type: python
	name: john
	owner: guido
	weight: 43
	eats: bugs

Here's what I know about Clarence:
	animal type: chicken
	name: clarence
	owner: tiffany
	weight: 2
	eats: seeds

Here's what I know about Peso:
	animal type: dog
	name: peso
	owner: eric
	weight: 37
	eats: shoes
# 3.喜欢的地方:
# 创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,
# 都存储他喜欢的 1~3 个地方。为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。
# 遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来
favorite_places = {
    'eric': ['bear mountain', 'death valley', 'tierra del fuego'],
    'erin': ['hawaii', 'iceland'],
    'ever': ['mt. verstovia', 'the playground', 'south carolina']
    }

for name, places in favorite_places.items():
    print("\n" + name.title() + " likes the following places:")
    for place in places:
        print("- " + place.title())
Eric likes the following places:
- Bear Mountain
- Death Valley
- Tierra Del Fuego

Erin likes the following places:
- Hawaii
- Iceland

Ever likes the following places:
- Mt. Verstovia
- The Playground
- South Carolina
# 4.喜欢的数字
# 使用一个字典来存储一些人喜欢的数字。请想出 5 个人的名字,并将这些名字用作字典中的键;
# 想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。打印每个人的名字和喜欢
# 的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
# 让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印出来
favorite_numbers = {
    'mandy': [42, 17],
    'micah': [42, 39, 56],
    'gus': [7, 12],
    }

for name, numbers in favorite_numbers.items():
    print("\n" + name.title() + " likes the following numbers:")
    for number in numbers:
        print("  " + str(number))
Mandy likes the following numbers:
  42
  17

Micah likes the following numbers:
  42
  39
  56

Gus likes the following numbers:
  7
  12
# 5.喜欢的城市
# 创建一个名为 cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,
# 并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。
# 在表示每座城市的字典中,应包含 country 、 population 和 fact 等键。
# 将每座城市的名字以及有关它们的信息都打印出来
cities = {
    'santiago': {
        'country': 'chile',
        'population': 6158080,
        'nearby mountains': 'andes',
        },
    'talkeetna': {
        'country': 'alaska',
        'population': 876,
        'nearby mountains': 'alaska range',
        },
    'kathmandu': {
        'country': 'nepal',
        'population': 1003285,
        'nearby mountains': 'himilaya',
        }
    }

for city, city_info in cities.items():
    country = city_info['country'].title()
    population = city_info['population']
    mountains = city_info['nearby mountains'].title()

    print("\n" + city.title() + " is in " + country + ".")
    print("  It has a population of about " + str(population) + ".")
    print("  The " + mountains + " mountains are nearby.")
Santiago is in Chile.
  It has a population of about 6158080.
  The Andes mountains are nearby.

Talkeetna is in Alaska.
  It has a population of about 876.
  The Alaska Range mountains are nearby.

Kathmandu is in Nepal.
  It has a population of about 1003285.
  The Himilaya mountains are nearby.
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YEGE学AI算法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值