字典(二)

套嵌

把字典储存在列表中或将列表作为值存储在字典中,这种方式称为套嵌!

1、字典列表

使用列表来包含不同类型的alien(同时每个alien类型对应一个字典)

第一步:创建字典

>>> 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语句,可以遍历整个列表,并且打印出来

>>> for alien in aliens:
...    print(alien)
...
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

通过range()函数,来批量创建每一类alien

>>> aliens=[]  # 第一步,创建一个空列表,用于存放批量创建出来的aliens #

>>> for alien_number in range(30):

...  new_alien = {'color':'green','points':5}

...  aliens.append(new_alien) 

# 循环30次,每次循环结果追加到列表aliens中 #

打印aliens列表中前6个元素

>>> for alien in aliens[:6]:
... print(alien)
...
{'points': 5, 'color': 'green'}
{'points': 5, 'color': 'green'}
{'points': 5, 'color': 'green'}
{'points': 5, 'color': 'green'}
{'points': 5, 'color': 'green'}
{'points': 5, 'color': 'green'}

这样批量创建出来的alien,每一个都是一模一样的,我们可以for 循环中通过if 判断来修改字典的值。

遍历aliens的切片(0-3)前三个,把颜色修改为:blue

>>> for alien in aliens[0:3]:
... if alien['color'] == 'green':
... alien['color'] = 'blue'
... print(alien)
...
{'points': 5, 'color': 'blue'}
{'points': 5, 'color': 'blue'}
{'points': 5, 'color': 'blue'}

 

2、在字典中存储列表

作用:每当需要在字典中讲一个键关联到多个值的时候,都可以在字典中套嵌一个列表。

favorite_languages = {

    'jan':['python','ruby'],

    'alben':['python','C++'],

    'edward':['ruby','go'],

    'phil':['java','C']

}

for name,languages in favorite_languages.items():

    print("\n" + name.title() + " 's favorite languages are:")

    for language in languages:

        print('\t' + language.title())

释义:

配置了一个字典,字典中键涵盖了四位人的名字:‘jan’、‘alben’,‘edward’,‘phil’

键的值对应的是列表,包含每个人喜欢的编程语言(有的元素=1,有的元素=2)

遍历字典的键值,并且进行条件判断同时打印输出结果

Edward 's favorite languages are:

        Ruby

        Go

 

Jan 's favorite languages are:

        Python

        Ruby

 

Alben 's favorite languages are:

        Python

        C++

 

Phil 's favorite languages are:

        Java

        C

note:\n 换行符  \t 制表符(左对齐的意思)

 

3、在字典中嵌套字典

键对应的值是另一个字典的键

举例:

创建用于存放用户名的字典,键=用户名,值用于存放另外一个字典,保存用户的姓、年龄、住址等额外信息

 

users = {

 

    'alben':{

 

        'first_name':'xue',

 

        'age':'26',

 

        'location':'wuxi',

 

    }  ,

 

    'nichole':{

 

        'first_name':'huang',

 

        'age':'23',

 

        'location':'shanghai'

 

    }  

 

}

#遍历这个字典,把用户名存储到变量username中,把用户其他信息存储到user_info中#

for username,user_info in users.items():

    print(username)

    print(user_info)

结果:

nichole
{'age': '23', 'location': 'shanghai', 'first_name': 'huang'}
alben
{'age': '26', 'location': 'wuxi', 'first_name': 'xue'}

 

posted @ 2017-05-06 22:25  alben-xue  阅读(216)  评论(0编辑  收藏  举报