Home > database >  Dict of list of list into dict of tuples of tuples
Dict of list of list into dict of tuples of tuples

Time:04-06

I have this dictionary:

a = {'Jimmy': [['5', '7', '5'], ['S', 'F', 'R']], 
     'Limerick': [['8', '8', '5', '5', '8'], ['A', 'A', 'B', 'B', 'A']]}

I want the end product to be a dictionary with tuples of tuples, but I think the second loop is not working.

What I want:

a = {'Jimmy': (('5', '7', '5'), ('S', 'F', 'R')), 
     'Limerick': (('8', '8', '5', '5', '8'), ('A', 'A', 'B', 'B', 'A'))}

Can anyone help me to see what I'm doing wrong?

I tried:

a = {'Jimmy': [['5', '7', '5'], ['S', 'F', 'R']], 
     'Limerick': [['8', '8', '5', '5', '8'], ['A', 'A', 'B', 'B', 'A']]}

for key in a:
    a[key] = tuple(a[key])
    for value in a[key]:
        value = tuple(value)
        
print(a)

but it didn't work.

CodePudding user response:

value refers to a fresh variable -- reassigning it does not modify the dictionary.

You should use map() to transform each list into a tuple, and then call tuple() once more to transform the resulting map object into a tuple:

for key in a:
    a[key] = tuple(map(tuple, a[key]))

CodePudding user response:

You are almost there. What you needed is this:

for key in a:
    a[key] = tuple(tuple(item) for item in a[key])

CodePudding user response:

Your statement value = tuple(value) re-assigns the local variable value to a new tuple, but it doesn't change the contents of a[key] at all.

In fact, since tuples are immutable, your statement a[key] = tuple(a[key]) prevents the contents of a[key] from changing, unless you reassign a[key] = something_else. Something like a[key] = tuple(a[key]) then a[key][0] = "A" will fail because tuples are immutable.

The other answers give nice concise solutions, so you may want to go with those, but here is one that mirrors your original attempt:

a = {'Jimmy': [['5', '7', '5'], ['S', 'F', 'R']], 
     'Limerick': [['8', '8', '5', '5', '8'], ['A', 'A', 'B', 'B', 'A']]}

for key in a:
    new_values = []
    for value in a[key]:
        new_values.append(tuple(value))
    a[key] = tuple(new_values)
        
print(a)

Here, to get around the fact that tuples are immutable, you can make a list [] (which is mutable), build it up over the loop, then convert the list to a tuple, and then finally assign that tuple to a[key].

  • Related