0

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.)

  • Please add your code, what have you attempted? In that way contributors can find and explain what's wrong with your code – EnriqueBet Dec 06 '21 at 06:06

2 Answers2

5

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
trincot
  • 317,000
  • 35
  • 244
  • 286
1

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)