输入:
a = (("s", 3), ("c", 6), ("s", 8))
dict(a)
输出:
{"s": 3, "c": 6}
我怎样才能得到以下结果?
{"s": (3, 8), "c": 6}
输入:
a = (("s", 3), ("c", 6), ("s", 8))
dict(a)
输出:
{"s": 3, "c": 6}
我怎样才能得到以下结果?
{"s": (3, 8), "c": 6}
>>> 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]})
使用setdefault()
并且c
应该是一个列表:
>>> 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]}
另一种选择是使用groupby
(虽然我会去defaultdict
),这意味着如果你需要它们,你可以很容易地留下元组:
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)) }