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.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加