Home > front end >  How do I convert from a list of tuples and integers to a nested dictionary?
How do I convert from a list of tuples and integers to a nested dictionary?

Time:12-06

I have a list containing tuples and integers
e.g.

mylist = [ (('ART', 'bar'), 2), (('ART', 'get'), 1), (('b', 'bet'), 1), (('b', 'chest'), 1), (('b', 'kart'), 2), (('b', 'zee'), 1)]

which I want to convert to this nested dictionary

my_dict = {
    "ART": {"bar": 2, "get": 1},
    "b": {"bet": 1, "chest": 1, "kart": 2,"zee": 1}
}

I've been trying to do this using for loops but I'm a beginner and I don't have any experience with nested dictionaries so I really don't know where to start. I've looked at other questions related to dictionaries of dictionaries e.g. this and this but the methods suggested aren't working for me (I assume because I am dealing with tuples rather than just lists of lists.)

CodePudding user response:

You could loop over the input and use setdefault to populate the dictionary:

my_dict = {}
for (key, prop), value in mylist:
    my_dict.setdefault(key, {})[prop] = value

CodePudding user response:

Try this:

mylist = [ (('ART', 'bar'), 2), (('ART', 'get'), 1), (('b', 'bet'), 1), 

(('b', 'chest'), 1), (('b', 'kart'), 2), (('b', 'zee'), 1)]
mydict = dict()

for i in mylist:
    if i[0][0] not in mydict.keys():
        mydict[i[0][0]] = {i[0][1]: i[1]}
    else:
        mydict[i[0][0]][i[0][1]] = i[1]
print(mydict)

CodePudding user response:

You can use collections.defaultdict:

from collections import defaultdict
my_dict = defaultdict(dict)
for (k1,k2),v in mylist:
    my_dict[k1][k2] = v
my_dict = dict(my_dict)

Output:

{'ART': {'bar': 2, 'get': 1}, 'b': {'bet': 1, 'chest': 1, 'kart': 2, 'zee': 1}}
  • Related