Reputation: 669
input:
a = (("s", 3), ("c", 6), ("s", 8))
dict(a)
output:
{"s": 3, "c": 6}
How can I get the following result?
{"s": (3, 8), "c": 6}
Upvotes: 0
Views: 678
Reputation: 142136
Another option is using groupby
(although I'd go defaultdict
) which means you can be left with tuples fairly easily if you need them:
from itertools import groupby
from operator import itemgetter as ig
a = (("s", 3), ("c", 6), ("s", 8))
newdict = { k:tuple(map(ig(1), v)) for k, v in groupby(sorted(a), ig(0)) }
Upvotes: 2
Reputation: 133534
>>> from collections import defaultdict
>>> a = (("s", 3), ("c", 6), ("s", 8))
>>> d = defaultdict(list)
>>> for c, num in a:
d[c].append(num)
>>> d
defaultdict(<type 'list'>, {'s': [3, 8], 'c': [6]})
Upvotes: 3
Reputation: 250921
use setdefault()
and c
should be a list:
>>> a = (("s",3), ("c",6), ("s",8))
>>> dic={}
>>> for x in a:
dic.setdefault(x[0],[]).append(x[1])
>>> dic
{'s': [3, 8], 'c': [6]}
Upvotes: 2