Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dict of list of list into dict of tuples of tuples

I had a very quick question. I’m fairly new to python : )

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 im 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 fully work.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading