[英]Python convert list of tuples to dictionary with value of multiple tuples
I don't what to do with this because I can't append tuples and I just showed it with list as default我不这样做,因为我不能 append 元组,我只是用默认列表显示它
Dict = dict()
def convert(list_tup):
for a,b,c in list_tup:
letters = a,b
number = c
Dict.setdefault(number,[]).append(letters)
# I only want a multiple tuple values not list of tuple
return Dict
strings = [('w', 'x','2'), ('y', 'z', '3')]
print(convert(strings))
it prints {'2': [('w', 'x')], '3': [('y', 'z')]}
它打印
{'2': [('w', 'x')], '3': [('y', 'z')]}
how can I add multiple tuples as value in one key?如何在一个键中添加多个元组作为值?
I want my output to be like this:我希望我的 output 是这样的:
{'2': ('w', 'x'), '3': ('y', 'z')}
The following dict comprehension should solve this以下dict理解应该解决这个问题
>>> {c: (a,b) for a,b,c in strings}
{'2': ('w', 'x'), '3': ('y', 'z')}
You can just make new entries in the output dictionary by keying c
for the value (a,b)
:您可以通过键入
c
的值(a,b)
在 output 字典中创建新条目:
def convert(list_tup):
d = {}
for a,b,c in list_tup:
letters = a,b
number = c
d[c] = (a,b)
return d
But Cory's answer is more但科里的回答更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.