存储路径到字典值 [英] Store path to dictionary value
本文介绍了存储路径到字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将路径存储在 dict
中 dict
中的值?例如,我们可以轻松地将路径存储在变量 name_field
中的名称
中:
person = {}
person ['name'] ='Jeff Atwood'
person ['address'] = {}
person ['address'] ['street'] ='Main Street'
person ['address'] ['zip'] ='12345'
person ['address'] [ 'city'] ='迈阿密'
#获取名称
name_field ='name'
print(person [name_field])
如何存储 city
值的路径?
#获取城市
city_field = ['地址','城市']
打印(person [city_field])//显然赢得'工作!
解决方案
您可以使用 / code>函数做这个
print reduce(lambda x,y:x [y],city_field,person )
输出
迈阿密
How might one store the path to a value in a dict
of dict
s? For instance, we can easily store the path to the name
value in a variable name_field
:
person = {}
person['name'] = 'Jeff Atwood'
person['address'] = {}
person['address']['street'] = 'Main Street'
person['address']['zip'] = '12345'
person['address']['city'] = 'Miami'
# Get name
name_field = 'name'
print( person[name_field] )
How might the path to the city
value be stored?
# Get city
city_field = ['address', 'city']
print( person[city_field] ) // Obviously won't work!
解决方案
You can use reduce
function to do this
print reduce(lambda x, y: x[y], city_field, person)
Output
Miami
这篇关于存储路径到字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文