Python字典理解:为key赋值,其中value是一个列表

时间:2018-05-02 12:19:38

标签: python dictionary

示例:

dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]}

应用此词典理解后:

another_dictionary = {key:value for (value,key) in dictionary.values()}

结果如下:

another_dictionary = {"string1": 5, "string2": 2}

换句话说,它不会在作为列表项的同一个键下汇总整数值。

=============================================== ==================

期望的结果:

another_dictionary = {"string1": 8, "string2": 2}

2 个答案:

答案 0 :(得分:5)

您可以使用// async/await can be used. it('works with async/await', async () => { expect.assertions(1); const data = await user.getUserName(4); expect(data).toEqual('Mark'); }); // async/await can also be used with `.resolves`. it('works with async/await and resolves', async () => { expect.assertions(1); await expect(user.getUserName(5)).resolves.toEqual('Paul'); });

collections.defaultdict

您的代码不起作用的原因是您没有指定任何求和或聚合逻辑。这将需要某种分组操作,或者在此处迭代并添加到新词典中的相关项目。

答案 1 :(得分:1)

您还可以使用itertools.groupby

import itertools
dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]}
d= {a:sum(c for _, [c, d] in b) for a, b in itertools.groupby(sorted(dictionary.items(), key=lambda x:x[-1][-1]), key=lambda x:x[-1][-1])}

输出:

{'string2': 2, 'string1': 8}