简体   繁体   中英

Python nested dictionary and nested update

I would like to update or create a nested dictionary without altering the existing content.

In the example below I will try to add the couple {'key2.2': 'value2.2'} nested as a child to the entry key2.

  • Case 1: the parent key (key2) exists:
    mydict = {'key1': 'value1', 'key2': {'key2.1': 'value2.1'}}
    mydict['key2'].update({'key2.2': 'value2.2'})
    pprint(mydict)

{'key1': 'value1', 'key2': {'key2.1': 'value2.1', 'key2.2': 'value2.2'}}

This is what I expected, no problem here.

  • Case 2: the parent key (key2) does not exists :*
    mydict = {'key1': 'value1'}
    mydict['key2'].update({'key2.2': 'value2.2'})

KeyError: 'key2'

Seems logic, so let's try something else..

    mydict = {'key1': 'value1'}
    mydict.update({'key2': {'key2.2': 'value2.2'}})
    pprint(mydict)

{'key1': 'value1', 'key2': {'key2.2': 'value2.2'}}

Perfect. Let's check if this works with case 1 too.

  • Case 1B: the parent key (key2) exists:
    mydict = {'key1': 'value1', 'key2': {'key2.1': 'value2.1'}}
    mydict.update({'key2': {'key2.2': 'value2.2'}})
    pprint(mydict)

{'key1': 'value1', 'key2': {'key2.2': 'value2.2'}}

The existing entry {'key2.1': 'value2.1'} got deleted, this is not what I want.

What would be the best way to achieve what I want? Like a nested update? I know this would be possible with a couple of try:/except KeyError:, but it doesn't seems very clean.

You could use defaultdict :

from collections import defaultdict

mydict = defaultdict(dict)
mydict.update({'key1': 'value1', 'key2': {'key2.1': 'value2.1'}})
mydict['key2'].update({'key2.2': 'value2.2'})
print(mydict)

mydict = defaultdict(dict)
mydict.update({'key1': 'value1'})
mydict['key2'].update({'key2.2': 'value2.2'})
print(mydict)

Outputs:

defaultdict(<class 'dict'>, {'key1': 'value1', 'key2': {'key2.1': 'value2.1', 'key2.2': 'value2.2'}})
defaultdict(<class 'dict'>, {'key1': 'value1', 'key2': {'key2.2': 'value2.2'}})

Try:

mydict = {'key1': 'value1', 'key2': {'key2.1': 'value2.1'}}
if "key2" in mydict:
    mydict["key2"].update({'key2.2': 'value2.2'})
else:
    mydict["key2"] = {'key2.2': 'value2.2'}

Code:

mydict = {'key1': 'value1', 'key2': {'key2.1': 'value2.1'}}
mydict['key2.2'.split('.')[0]].update({'key2.2' : 'value2.2'})
print(mydict)

Output:

{'key2': {'key2.2': 'value2.2', 'key2.1': 'value2.1'}, 'key1': 'value1'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM