Reputation: 3175
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}}
Upvotes: 2
Views: 701
Reputation: 22041
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.
Upvotes: 0
Reputation: 5902
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}}
Upvotes: 0
Reputation: 474021
How about using 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}})
Upvotes: 4