I have a list of tuples, say:
list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
I need to get correspoding values for any (unique) second element in a tuple. For example as a dictionary. Output:
dict = {1:['a','c'],2:['b','a'],3:['d']}
Whats the most pythonic way of doing it? Help much appriciated!
I'd probably go with a defaultdict
like jamylak, but if you want a "real" dictionary, you can use setdefault()
:
>>> list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
>>> d = {}
>>> for item in list_of_tuples:
... d.setdefault(item[1],[]).append(item[0])
...
>>> d
{1: ['a', 'c'], 2: ['b', 'a'], 3: ['d']}
>>> from collections import defaultdict
>>> list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
>>> d = defaultdict(list)
>>> for c,num in list_of_tuples:
d[num].append(c)
>>> d
defaultdict(<type 'list'>, {1: ['a', 'c'], 2: ['b', 'a'], 3: ['d']})
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.