简体   繁体   English

从元组列表创建嵌套字典

[英]Creating a nested dictionary from a list of tuples

I have a list of tuples as shown below. 我有一个元组列表,如下所示。 I want to create a nested dictionary where the first element in the tuple is key and the values with the same keys should be grouped into the same key as a dictionary. 我想创建一个嵌套的字典,其中元组中的第一个元素是键,并且具有相同键的值应分组为与字典相同的键。

This is what I tried but it doesn't give me the nested dictionary I wanted. 这是我尝试过的方法,但没有给我想要的嵌套字典。

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}})

Desired result: 所需结果:

 {37043: {2862826: 1, 2850223: 1}, 37107: {2847978:1, 2848001: 1, 2844725: 1}}

How about using defaultdict(dict) : 如何使用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}})

Code below would suit your: 以下代码适合您:

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 to setdefault method documentation. 链接setdefault方法文档。

The following does with plain key-value assignment: 以下是简单的键值分配:

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}

Output: 输出:

{37043: {2862826: 1, 2850223: 1}, 37107: {2848001: 1, 2847978: 1, 2844725: 1}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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