gpt4 book ai didi

python - 在python中将列表转换为字典

转载 作者:太空宇宙 更新时间:2023-11-04 07:21:13 25 4
gpt4 key购买 nike

我有一个 python 字典的形式:

a1 = {
'SFP_1': ['cat', '3'],
'SFP_0': ['cat', '5', 'bat', '1']
}

我需要的最终结果是以下形式的字典:

{'bat': '1', 'cat': '8'}

我目前正在这样做:

b1 = list(itertools.chain(*a1.values()))
c1 = dict(itertools.izip_longest(*[iter(b1)] * 2, fillvalue=""))

这给了我输出:

>>> c1
{'bat': '1', 'cat': '5'}

我可以遍历字典并得到它,但是谁能给我一个更 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'}

关于python - 在python中将列表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17986923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com