[英]Unpacking a tuple with dictionaries in Python
I have a tuple with multiple dictionaries and I wish to unpack them for further use. 我有一个带有多个字典的元组,我希望将它们拆包以备将来使用。
Let's say I have this: 假设我有这个:
tuple_to_add = {'name': 'custom1', 'value': 'first value'},{'name': 'custom2', 'value': 'second value'}
And I'd like to iterate through them I tried something like that but it didn't give me my answer: 我想遍历他们,我尝试了类似的方法,但没有给出我的答案:
for value, name in tuple_to_add:
print(value)
print(name)
Dictionaries can't be unpacked in a way tuples and lists can. 字典无法以元组和列表的方式进行打包。 If you had a tuple of tuples, your way of printing would work just fine:
如果您有一个元组,那么您的打印方式就可以了:
tuple_to_add = ('custom1', 'first value'), ('custom2', 'second value')
for name, value in tuple_to_add:
# do whatever you want
You can simply iterate over the tuple and get the actual dictionary objects which you can use to get all the necessary information: 您可以简单地遍历元组并获取实际的字典对象,这些对象可用于获取所有必要的信息:
for dc in tuple_to_add:
print(dc['value'])
print(dc['name'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.