[英]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. value
指的是一个新变量——重新分配它不会修改字典。
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:您应该使用
map()
将每个列表转换为元组,然后再次调用tuple()
将结果 map object 转换为元组:
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.您的语句
value = tuple(value)
将局部变量value
重新分配给一个新的元组,但它根本不会更改a[key]
的内容。
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
.事实上,由于元组是不可变的,您的语句
a[key] = tuple(a[key])
会阻止 a a[key]
key] 的内容发生变化,除非您重新分配a[key] = something_else
。 Something like a[key] = tuple(a[key])
then a[key][0] = "A"
will fail because tuples are immutable.像
a[key] = tuple(a[key])
then a[key][0] = "A"
这样的东西会失败,因为元组是不可变的。
The other answers give nice concise solutions, so you may want to go with those, but here is one that mirrors your original attempt:其他答案给出了简洁明了的解决方案,因此您可能希望使用这些解决方案 go,但这里有一个反映了您最初的尝试:
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]
.在这里,为了解决元组不可变的事实,您可以制作一个列表
[]
(可变的),在循环中构建它,然后将列表转换为元组,最后将该元组分配给a[key]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.