I don't what to do with this because I can't append tuples and I just showed it with list as default
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')]}
how can I add multiple tuples as value in one key?
I want my output to be like this:
{'2': ('w', 'x'), '3': ('y', 'z')}
The following dict comprehension should solve this
>>> {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)
:
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
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.