我有一个元组列表,如下所示。我想创建一个嵌套字典,其中元组中的第一个元素是键,具有相同键的值应该被分组到与字典相同的键中。
这是我尝试的但是它没有给我我想要的嵌套字典。
data = [(37043, 2862826), (37043,2850223), (37107,2847978), (37107,2848001), (37107,2844725)]
data_dict = defaultdict(list)
for key, value in data:
value = {value:1}
data_dict[key].append(value)
print (data_dict)
>>> defaultdict(<class 'list'>, {37043: [{2862826: 1}, {2850223: 1}], 37107: [{2847978: 1}, {2848001: 1}, {2844725: 1}]})
data_dict = defaultdict(dict)
for key, value in data:
value = {value:1}
data_dict[key] = value
print (data_dict)
>>> defaultdict(<class 'dict'>, {37043: {2850223: 1}, 37107: {2844725: 1}})
期望的结果:
{37043: {2862826: 1, 2850223: 1}, 37107: {2847978:1, 2848001: 1, 2844725: 1}}
答案 0 :(得分:4)
如何使用defaultdict(dict)
:
>>> data_dict = defaultdict(dict)
>>> for key, value in data:
... data_dict[key][value] = 1
...
>>> data_dict
defaultdict(<type 'dict'>, {37043: {2862826: 1, 2850223: 1}, 37107: {2848001: 1, 2847978: 1, 2844725: 1}})
答案 1 :(得分:0)
以下代码适合您:
data = [(37043, 2862826), (37043,2850223), (37107,2847978), (37107,2848001), (37107,2844725)]
data_map = {}
for key, value in data:
data_map.setdefault(key, {})
data_map[key][value] = 1
print data_map
# {37043: {2862826: 1, 2850223: 1}, 37107: {2848001: 1, 2847978: 1, 2844725: 1}}
Link到setdefault
方法文档。
答案 2 :(得分:0)
以下是普通键值赋值:
data = [(37043, 2862826), (37043,2850223), (37107,2847978), (37107,2848001), (37107,2844725)]
output = {}
for key,value in data:
if key in output:
if value in output[key]: output[key][value] += 1
else: output[key][value] = 1
else: output[key] = {value:1}
输出:
{37043: {2862826: 1, 2850223: 1}, 37107: {2848001: 1, 2847978: 1, 2844725: 1}}