So i have a list of typles: x= [('0', '0', '20'), ('0', '0', '25'),('0', '3', '28'), ('1', '1', '74'), ('1', '1', '2')]
I want to create a nested dictionary by iterating the original (not addding them manually) to get:
dictionary= {'0': {'0': ('20', '25')},{'3': ('28')} , '1': {'1': ('74', '2')}}
In other words, in the list of tuples, group them by: the first element of the tuples being the key, the second the subkey and the third the value of the subkey.
- If two tuples have the same key and subkey we add the value to the values (i.e.{'0':'0': ('20', '25')}
- If they have the same key but different subkey, we add a subkey,key pair under the same key (i.e.{'0':{'0': ('20', '25')},{'3': ('28')}}
How would the code be?
CodePudding user response:
x = [('0', '0', '20'), ('0', '0', '25'),('0', '3', '28'), ('1', '1', '74'), ('1', '1', '2')]
a = {}
def add_dict2(innerdict, ele2, ele3):
if not innerdict.get(ele2):
innerdict[ele2] = []
innerdict[ele2].append(ele3)
def add_dict(elel, ele2, ele3):
if not a.get(ele1):
a[ele1] = {}
add_dict2(a[ele1], ele2, ele3)
for (ele1, ele2, ele3) in x:
add_dict(ele1, ele2, ele3)
print(a)
Prints
{'0': {'0': ['20', '25'], '3': ['28']}, '1': {'1': ['74', '2']}}
CodePudding user response:
Try the following :
x = [('0','0','20'),('0','0','25'),('0','3','28'),('1','1','74'),('1','1','2')]
from collections import defaultdict
your_dict = defaultdict(dict)
for row in x:
your_dict[row[0]][row[1]] = tuple([n for n in [r[2] for r in x if r[1] == row[1]]])
Your precise expected output:
{'0': {'0': ('20','25'), '3': ('28')}, '1': {'1': ('74','2')}})
CodePudding user response:
If you can use list
instead of tuple
for nested dictionary
you can try this:
from collections import defaultdict
dct = defaultdict(lambda : defaultdict(list))
x= [('0', '0', '20'), ('0', '0', '25'),('0', '3', '28'), ('1', '1', '74'), ('1', '1', '2')]
for item in x:
dct[item[0]][item[1]].append(item[2])
print(dct)
Output:
defaultdict(<function <lambda> at 0x7fed4026a040>, {'0': defaultdict(<class 'list'>, {'0': ['20', '25'], '3': ['28']}), '1': defaultdict(<class 'list'>, {'1': ['74', '2']})})
>>> dct['0']
defaultdict(list, {'0': ['20', '25'], '3': ['28']})
>>> dct['0']['0']
['20', '25']
>>> dct['1']
defaultdict(list, {'1': ['74', '2']})
>>> dct['1']['1']
['74', '2']