具有词典列表:
list_dict = [['key1', {'subkey1': 0}],
['key1', {'subkey2': 2}],
['key1', {'subkey5': 5}],
['key2', {'subkey2': 4}],
['key2', {'subkey1': 8}],
['key1', {'sybkey5': 10}]]
如何将list_dict
转换为整洁的字典,如下所示?
{'key1': {'subkey1': 0, 'subkey2': 2, 'subkey5': 5},
'key2': {'subkey2': 4, 'subkey1': 8, 'sybkey5': 10}}
答案 0 :(得分:3)
以下方法应该起作用:
d = dict()
for item in list_dict:
d.setdefault(item[0], {}).update(item[1])
setdefault(key [,default])
如果key在字典中,则返回其值。如果不是,请插入具有默认值的密钥,然后返回默认值。默认默认为无。
答案 1 :(得分:1)
您可以使用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
输出:
defaultdict(dict,
{'key1': {'subkey1': 0, 'subkey2': 2, 'subkey5': 5, 'sybkey5': 10},
'key2': {'subkey2': 4, 'subkey1': 8}})
或者您可以使用dict.setdefault
,它有点慢:
d = {}
for k, v in list_dict:
d.setdefault(k, {}).update(v)
输出:
{'key1': {'subkey1': 0, 'subkey2': 2, 'subkey5': 5, 'sybkey5': 10},
'key2': {'subkey2': 4, 'subkey1': 8}}
答案 2 :(得分:0)
这有效:
//First create a 'Driver' instance.
var driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "neo"), Config.Builder.WithEncryptionLevel(EncryptionLevel.None).ToConfig());
//Pass that driver to the BoltGraphClient
var bgc = new BoltGraphClient(driver);
//Connect.
bgc.Connect();
答案 3 :(得分:0)
常规方法
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]