How can I convert list of tuples like:
query_res = [('a3','b6','c1'),
('a3','b6','c2'),
('a3','b6','c3'),
('a3','b7','c4'),
('a4','b8','c5'),
('a4','b8','c6')]
to a dict like:
result = {
'a3': {
'b6': ['c1', 'c2', 'c3'],
'b7': ['c4']
},
'a4': {
'b8': ['c5', 'c6']
}
}
I have tried defaultdict, bug can only get inner dict, how can I map a
to res
here?:
res = defaultdict(list)
for a, b, c in query_res:
res[b].append(c)
Using dict.setdefault
Ex:
query_res = [('a3','b6','c1'),
('a3','b6','c2'),
('a3','b6','c3'),
('a3','b7','c4'),
('a4','b8','c5'),
('a4','b8','c6')]
result = {}
for key, subkey, value in query_res:
result.setdefault(key, {}).setdefault(subkey, []).append(value)
print(result)
Output:
{'a3':
{'b6': ['c1', 'c2', 'c3'],
'b7': ['c4']
},
'a4':
{'b8': ['c5', 'c6']
}
}
You can nest defaultdict
s:
from collections import defaultdict
import pprint
d = defaultdict(lambda: defaultdict(list))
for a, b, c in query_res:
d[a][b].append(c)
pprint.pprint(d)
Output:
defaultdict(<function <lambda> at 0x10acb1f28>,
{'a3': defaultdict(<class 'list'>,
{'b6': ['c1', 'c2', 'c3'],
'b7': ['c4']}),
'a4': defaultdict(<class 'list'>, {'b8': ['c5', 'c6']})})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With