考虑一个持有人的词典:
person = {}
person['name'] = 'Jeff Atwood'
person['address'] = {}
person['address']['street'] = 'Main Street'
person['address']['zip'] = '12345'
person['address']['city'] = 'Miami'
如何存储字典中某个位置的路径以写入该值?
# Set city (Existing field)
city_field = ['address', 'city']
person[city_field] = 'London' // Obviously won't work!
# Set country (New field)
country_field = ['address', 'country']
person[city_country] = 'UK' // Obviously won't work!
请注意,我之前曾问过how to store the path to dictionary value for reading。
答案 0 :(得分:1)
使用元组作为索引。
city_field = ('address', 'city')
country_field = ('address', 'country')
用法:
>>> person = {}
>>> city_field = ('address', 'city')
>>> country_field = ('address', 'country')
>>> person[city_field] = 'Miami'
>>> person[country_field] = 'UK'
>>> person
{('address', 'country'): 'UK', ('address', 'city'): 'Miami'}
答案 1 :(得分:0)
知道了!实际上我的同事Moshe是这个背后的大脑:
def set_path(someDict, path, value):
for x in path[::-1]:
value = {x: value}
return deepupdate(someDict, value)
def deepupdate(original, update):
for key, value in original.items():
if not key in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update
person = {}
person = set_path(person, ['name'], 'Shalom')
person = set_path(person, ['address', 'city'], 'Toronto')
person = set_path(person, ['address', 'street'], 'Baddessa')
pprint(person)
返回:
{
'address': {
'city': 'Toronto',
'street': 'Baddessa'
},
'name': 'Shalom'
}
这取决于用户Stanislav的优秀recursive dictionary deepmerge() function。