Python学习之路day02——007字典的嵌套

一、字典的嵌套

      有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。你
可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。

1、字典与列表的嵌套

        字典alien_0包含一个外星人的各种信息,但无法存储第二个外星人的信息,更别说屏幕上
全部外星人的信息了。如何管理成群结队的外星人呢?一种办法是创建一个外星人列表,其中每
个外星人都是一个字典,包含有关该外星人的各种信息。例如,下面的代码创建一个包含三个外
星人的列表:

alien_0 = {'color': 'green', 'points': 5}   #外星人1号字典
alien_1 = {'color': 'yellow', 'points': 10} #外星人2号字典
alien_2 = {'color': 'red', 'points': 15}      #外星人3号字典
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}

例子:添加30个外星,并输出前五个外星人的信息

aliens = []
set_number =30
point_number=5
for alien_number in range(set_number):
         new_alien={"color":"green","point":point_number,"speed":"slow"}
         aliens.append(new_alien)
         point_number= point_number+2
for alien in aliens[:5]:
         print(alien)

结果:

{'color': 'green', 'point': 5, 'speed': 'slow'}
{'color': 'green', 'point': 7, 'speed': 'slow'}
{'color': 'green', 'point': 9, 'speed': 'slow'}
{'color': 'green', 'point': 11, 'speed': 'slow'}
{'color': 'green', 'point': 13, 'speed': 'slow'}

2、字典中嵌套列表

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。

favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():

       if  len( languages) >1: #此处languages已经被默认为了 值
               print("\n" + name.title() + "'s favorite languages are:")

        else :

                print("\n" + name.title() + "'s favorite languages is:")
       for language in languages:
             print("\t" + language.title())

结果:

Jen's favorite languages are:
Python
Ruby
Sarah's favorite languages are:
C
Phil's favorite languages are:
Python
Haskell
Edward's favorite languages are:
Ruby
Go

3、字典中嵌套字典

users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
      print("\nUsername: " + username)
      full_name = user_info['first'] + " " + user_info['last']
      location = user_info['location']
      print("\tFull name: " + full_name.title())
      print("\tLocation: " + location.title())

结果:

Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris

 

 

猜你喜欢

转载自www.cnblogs.com/jokerwang/p/9254918.html