Is there any trick in order to easily transform a list to a dict with this specific format? I have been unable to do so.
FROM :
a = [
('A', 'B', 8),
('A', 'D', 10),
('A', 'E', 12),
('B', 'C', 6),
('B', 'F', 12),
('C', 'F', 8),
('D', 'E', 10),
('D', 'G', 30),
('E', 'F', 10),
('F', 'G', 12)
]
TO :
b = {
"A": {"B": 8, "D": 10, "E": 12},
"B": {"C": 6, "F": 12},
"C": {"F": 8},
"D": {"E": 10, "G": 30},
"E": {"F": 10},
"F": {"G": 12}
}
Thanks in advance you your tips
CodePudding user response:
Use defaultdict
from collections module:
from collections import defaultdict
b = defaultdict(dict)
for k, k1, v in a:
b[k].update({k1: v})
Output:
>>> b
defaultdict(dict,
{'A': {'B': 8, 'D': 10, 'E': 12},
'B': {'C': 6, 'F': 12},
'C': {'F': 8},
'D': {'E': 10, 'G': 30},
'E': {'F': 10},
'F': {'G': 12}})
An alternative version without defaultdict
:
b = {}
for k, k1, v in a:
t = b.setdefault(k, {})
t[k1] = v
CodePudding user response:
loop the list, check if the key is in the dict. if it is then add to the dict of that key. if its not then create the keys dict:
a = [
('A', 'B', 8),
('A', 'D', 10),
('A', 'E', 12),
('B', 'C', 6),
('B', 'F', 12),
('C', 'F', 8),
('D', 'E', 10),
('D', 'G', 30),
('E', 'F', 10),
('F', 'G', 12)
]
final_list = {}
for item in a:
if item[0] in final_list.keys():
final_list[item[0]][item[1]] = item[2]
else:
final_list[item[0]] = {item[1]: item[2]}
print(final_list)
CodePudding user response:
If the first level keys are in grouped order, you can use groupby from itertools in a dictionary comprehension:
from itertools import groupby
d = { k:{c:n for _,c,n in v} for k,v in groupby(a,key=lambda t:t[0]) }
print(d)
{'A': {'B': 8, 'D': 10, 'E': 12},
'B': {'C': 6, 'F': 12},
'C': {'F': 8},
'D': {'E': 10, 'G': 30},
'E': {'F': 10},
'F': {'G': 12}}
CodePudding user response:
Here's a beginner-friendly code.
- We unpack the tuple and put the values in individual variables
- If the key is already in
dic
, it means that a dictionary already exists and we simply add another pair. - Else, we make a new key value pair inside
dic
wherein the value is a dictionary.
list = [
('A', 'B', 8),
('A', 'D', 10),
('A', 'E', 12),
('B', 'C', 6),
('B', 'F', 12),
('C', 'F', 8),
('D', 'E', 10),
('D', 'G', 30),
('E', 'F', 10),
('F', 'G', 12)
]
dic = {}
for tuple in list:
key, element, num = tuple
if key in dic:
dic[key][element] = num
else:
dic[key] = {element: num}
for k, v in dic.items():
print(f"{k}: {v}")
Output:
{
"A": {"B": 8, "D": 10, "E": 12},
"B": {"C": 6, "F": 12},
"C": {"F": 8},
"D": {"E": 10, "G": 30},
"E": {"F": 10},
"F": {"G": 12}
}