I have an assignment to do this things without import any helpful function, could you guys help me? Thanks!
data = [
['num','e1','e2','e3'],
['2002','p','r','i'],
['2002','k','r','i'],
['2001','k','r','e'],
['2004','p','a','p'],
['2004','p','s','f']
]
newlist = [
{'num': '2001', 'e1': 'k', 'e2': 'r', 'e3': 'e'},
{'num': '2002', 'e1': 'p', 'e2': 'r', 'e3': 'i'},
{'num': '2002', 'e1': 'k', 'e2': 'r', 'e3': 'i'},
{'num': '2004', 'e1': 'p', 'e2': 'a', 'e3': 'p'},
{'num': '2004', 'e1': 'p', 'e2': 's', 'e3': 'f'}
]
How can I convert newlist into this by num is main key and next key is e1
{
'2001':{
'k':[{'num': '2001', 'e1': 'k', 'e2': 'r', 'e3': 'e'}]
},
'2002':{
'k':[{'num': '2002', 'e1': 'k', 'e2': 'r', 'e3': 'i'}],
'p':[{'num': '2002', 'e1': 'p', 'e2': 'r', 'e3': 'i'}]
},
'2004':{
'p':[{'num': '2004', 'e1': 'p', 'e2': 'a', 'e3': 'p'}, {'num': '2004', 'e1': 'p', 'e2': 's', 'e3': 'f'}]
}
}
2001 and 2002 have only k and k have only one data so it will be the only one member of k
you will see its form { num: {e1: [ {'num':..., 'e1': ..., 'e2': ... }, ... ], ...}, ... }
One way would be to loop through the input list (
dataornewlist) and use.setdefaultand.appendto fill up the nested dictionary or lists.To get the nested dictionary from
data:To get the nested dictionary from
newlist:You can also use dictionary comprehension to create a nested dictionary containing empty lists and then loop through
dataornewlistand add each dictionary in the input list to whichever list it belongs to in the nested dictionary.(You could filter the input list for each nested key right away with list comprehension when you're defining the nested dictionary, but doing it in a separate loop actually reduces the total number of times you loop through the input data.)
To get the nested dictionary from
data, you can useTo get the nested dictionary from
newlist, you can useWhichever approach is taken,
resultshould look like