天天看点

python字典嵌套分层查询_浅析python 字典嵌套

为什么需要嵌套?

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

字典列表

例如:字典alien_0包含一个外星人的信息,但无法存储第二个外星人的信息。怎么办呢?

我们可以创建三个外星人字典,那么问题来了,我们需要的是大量的外星人,有没有更简单的方式呢?

alien_0 = {'color':'blue','points':'5'}

alien_1 = {'color':'blue','points':'5'}

alien_2 = {'color':'blue','points':'5'}

aliens = []

for number in range(5):

new_alient = {'color':'blue','points':'5','speed':'slow'}

aliens.append(new_alient)

for i in aliens:

print(i)

print(str(len(aliens)))

输出

{'color': 'blue', 'points': '5', 'speed': 'slow'}

{'color': 'blue', 'points': '5', 'speed': 'slow'}

{'color': 'blue', 'points': '5', 'speed': 'slow'}

{'color': 'blue', 'points': '5', 'speed': 'slow'}

{'color': 'blue', 'points': '5', 'speed': 'slow'}

5

这些外星人都有相同的特征。在python看来,每个外星人都是独立的,但是这样并不符合业务需求。

例如:将前三个外星人修改成黄色、速度中等且值为10个点

aliens = []

for number in range(5):

new_alient = {'color':'blue','points':'5','speed':'slow'}

aliens.append(new_alient)

for alien in aliens[:3]:

if alien['color'] == 'blue':

alien['color'] = 'yellow'

alien['speen'] = 'medium'

alien['points'] = 10

for alien in aliens:

print(alien)

输出

{'color': 'yellow', 'points': 10, 'speed': 'slow', 'speen': 'medium'}

{'color': 'yellow', 'points': 10, 'speed': 'slow', 'speen': 'medium'}

{'color': 'yellow', 'points': 10, 'speed': 'slow', 'speen': 'medium'}

{'color': 'blue', 'points': '5', 'speed': 'slow'}

{'color': 'blue', 'points': '5', 'speed': 'slow'}

这里还可以使用if-elif-else语句,更加详细的表述每个外星人的属性。

在字典中存储列表

例如:买煎饼果子的时候,使用列表的话可以描述煎饼果子可以加什么配料。如果使用字典,不仅能描述配料,还能描述煎饼果子的产地等信息

jbgz = {'origin':'天津','toppings':['鸡蛋','香肠']}

print('煎饼果子产地是:' + jbgz['origin'] + '。你可以选择添加:')

for topping in jbgz['toppings']:

print(topping)

输出

煎饼果子产地是:天津。你可以选择添加:

鸡蛋

香肠

例如:调查程序员们喜欢都喜欢什么编程语言

languages = {

'jens':['python','java'],

'sarah':['c','ruby'],

'hack':['go']

}

for name,language in languages.items():

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

for i in language:

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

输出

jens's favorite languages are:

python

java

sarah's favorite languages are:

c

ruby

hack's favorite languages are:

go

在字典中存储字典

例如:网站内存储每个用户的姓、名、住址,访问这些信息

users = {

'岳云鹏':{

'姓':'岳',

'名':'龙刚',

'住址':'北京'

},

'孟鹤堂':{

'姓':'孟',

'名':'祥辉',

'住址':'北京'

}

}

for username,user_info in users.items():

print('\n艺名:'+ username)

full_name = user_info['姓'] + '' + user_info['名']

location = user_info['住址']

print('\t姓名:' + full_name)

print('\t住址:' + location)

输出

艺名:岳云鹏

姓名:岳龙刚

住址:北京

艺名:孟鹤堂

姓名:孟祥辉

住址:北京

以上就是浅析python 字典嵌套的详细内容,更多关于python 字典嵌套的资料请关注萬仟网其它相关文章!

希望与广大网友互动??

点此进行留言吧!