0
How to convert a nested list to a nested dictionary?I tried a lot but couldn't figure ir out. Can someone please help me.
If my list is. [[1,"Alex","female"],[2,"mark","male],[3,"Zoe","female"]] I want to convert this into nested dictionary - {1:{"no":1,"name":"Alex","gender":"female"},{2:{"no":2,"name":"mark","gender":"male"},{3:{"no":3,"name":"zoe","gender":"female"}} I code in python 3 so it would be helpful if u could also do it in python 3
1 Antwort
+ 2
import collections
L = [[0,[1,1.0]], [0,[2,0.5]], [1,[3,3.0]], [2,[1,0.33]], [2,[4,1.5]]]
d = collections.defaultdict(dict) for k, (sub_k, v) in L:
d[k][sub_k] = v print(dict(d))
# The output:
{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
More info regarding the above:
https://docs.python.org/3.3/library/collections.html