首页 > 解决方案 > 使用字典理解将 2 个列表转换为字典

问题描述

我有 2 个列表,我想使用字典理解将其转换为字典。

aa = ['07:51:59', '07:53:35', '07:55:20', '08:01:48']
bb = [50769054, 183926374, 183926374, 183926374]

输出应该是这样的:

{50769054:['07:51:59'], 183926374:['07:53:35', '07:55:20', '08:01:48']}

我正在尝试这种方式:

dictionary ={}
{bb[k]:aa[k] if bb[k] not in dictionary.keys() else dictionary[bb[k]].append(aa[k]) for k in range(0,4)}

但它只给我单一的价值。我的输出:

{50769054: ['07:51:59'], 183926374: ['08:01:48']}

标签: pythondictionary

解决方案


@Sushanth 的解决方案是准确的。在这种情况下,您可以像这样使用理解:

from collections import defaultdict

aa = ['07:51:59', '07:53:35', '07:55:20', '08:01:48']
bb = [50769054, 183926374, 183926374, 183926374]

dictionary = defaultdict(list)
[dictionary[y].append(x) for x, y in zip(aa, bb)]

print(dict(dictionary))

输出:

{50769054: ['07:51:59'], 183926374: ['07:53:35', '07:55:20', '08:01:48']}

推荐阅读