简体   繁体   中英

Construct a dictionary from a list of dictionary keys, sub-keys and values

Have a list of dictionaries:

list_dict = [['key1', {'subkey1': 0}],
             ['key1', {'subkey2': 2}],
             ['key1', {'subkey5': 5}],
             ['key2', {'subkey2': 4}],
             ['key2', {'subkey1': 8}],
             ['key1', {'sybkey5': 10}]]

How can list_dict be converted to a neat dictionary as follows?

{'key1': {'subkey1': 0, 'subkey2': 2, 'subkey5': 5},
 'key2': {'subkey2': 4, 'subkey1': 8, 'sybkey5': 10}}

The following should work:

d = dict()
for item in list_dict:
    d.setdefault(item[0], {}).update(item[1])

From the Python 3 Documentation :

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

you can use collections.defaultdict :

from collections import defaultdict


list_dict = [['key1', {'subkey1': 0}],
             ['key1', {'subkey2': 2}],
             ['key1', {'subkey5': 5}],
             ['key2', {'subkey2': 4}],
             ['key2', {'subkey1': 8}],
             ['key1', {'sybkey5': 10}]]

d = defaultdict(dict)

for k, v in list_dict:
    d[k].update(v)
d

output:

defaultdict(dict,
            {'key1': {'subkey1': 0, 'subkey2': 2, 'subkey5': 5, 'sybkey5': 10},
             'key2': {'subkey2': 4, 'subkey1': 8}})

or you can use dict.setdefault which is a bit slower:

d = {}
for k, v in list_dict:
    d.setdefault(k, {}).update(v)

output:

{'key1': {'subkey1': 0, 'subkey2': 2, 'subkey5': 5, 'sybkey5': 10},
 'key2': {'subkey2': 4, 'subkey1': 8}}

This works:

>>> from collections import defaultdict
>>> result = defaultdict(dict)
>>> for item in list_dict :
...     result[item[0]].update(item[1])
... 
>>> result
defaultdict(<type 'dict'>, {'key2': {'subkey2': 4, 'subkey1': 8}, 'key1': {'subkey5': 5, 'subkey2': 2, 'sybkey5': 10, 'subkey1': 0}})
>>> 

conventional approach

new_dict = {}
for i in list_dict:
    if i[0] in new_dict.keys():
            new_dict[i[0]].update(i[1])
    else:
            new_dict[i[0]]=i[1]

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