简体   繁体   中英

Dict of list of list into dict of tuples of tuples

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.

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

You are almost there. What you needed is this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM