0

考虑一个包含一个人的字典:

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!

请注意,我之前曾询问过如何存储字典值的路径以供阅读

4

2 回答 2

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'}
于 2013-11-07T15:00:55.450 回答
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 出色的递归字典 deepmerge() 函数

于 2013-11-07T19:06:20.127 回答