dotancohen
dotancohen

Reputation: 31471

Store path to dictionary value for setting value

Consider a dict that holds a person:

person = {}
person['name'] = 'Jeff Atwood'
person['address'] = {}
person['address']['street'] = 'Main Street'
person['address']['zip'] = '12345'
person['address']['city'] = 'Miami'

How might the path to a location in the dictionary be stored for writing to the value?

# 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!

Note that I had previously asked how to store the path to dictionary value for reading.

Upvotes: 0

Views: 191

Answers (2)

dotancohen
dotancohen

Reputation: 31471

Got it! Actually my co-worker Moshe is the brains behind this one:

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)

Returns:

{
    'address': {
        'city': 'Toronto',
        'street': 'Baddessa'
    },
    'name': 'Shalom'
}

This depends on user Stanislav's excellent recursive dictionary deepmerge() function.

Upvotes: 0

user1907906
user1907906

Reputation:

Use tuples as index.

city_field = ('address', 'city')    
country_field = ('address', 'country')

Usage:

>>> person = {}
>>> city_field = ('address', 'city')    
>>> country_field = ('address', 'country')
>>> person[city_field] = 'Miami'
>>> person[country_field] = 'UK'
>>> person
{('address', 'country'): 'UK', ('address', 'city'): 'Miami'}

Upvotes: 1

Related Questions