我有一个形式的python字典:
a1 = {
'SFP_1': ['cat', '3'],
'SFP_0': ['cat', '5', 'bat', '1']
}
Run Code Online (Sandbox Code Playgroud)
我需要的最终结果是表格的字典:
{'bat': '1', 'cat': '8'}
Run Code Online (Sandbox Code Playgroud)
我目前正在这样做:
b1 = list(itertools.chain(*a1.values()))
c1 = dict(itertools.izip_longest(*[iter(b1)] * 2, fillvalue=""))
Run Code Online (Sandbox Code Playgroud)
这给了我输出:
>>> c1
{'bat': '1', 'cat': '5'}
Run Code Online (Sandbox Code Playgroud)
我可以迭代字典并得到这个,但任何人都可以给我一个更pythonic方式做同样的事情?
使用defaultdict:
import itertools
from collections import defaultdict
a1 = {u'SFP_1': [u'cat', u'3'], u'SFP_0': [u'cat', u'5', u'bat', u'1']}
b1 = itertools.chain.from_iterable(a1.itervalues())
c1 = defaultdict(int)
for animal, count in itertools.izip(*[iter(b1)] * 2):
c1[animal] += int(count)
# c1 => defaultdict(<type 'int'>, {u'bat': 1, u'cat': 8})
c1 = {animal: str(count) for animal, count in c1.iteritems()}
# c1 => {u'bat': '1', u'cat': '8'}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
900 次 |
| 最近记录: |