繁体   English   中英

使用字典理解将 2 个列表转换为字典

[英]Convert 2 lists into a dictionary using dictionary comprehension

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

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

Output 应该像:

{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)}

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

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

试试这个, defaultict使用zip

from collections import defaultdict

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

result = defaultdict(list)

for x, y in zip(aa, bb):
    result[y].append(x)

defaultdict(<class 'list'>, {50769054: ['07:51:59'], 183926374: ['07:53:35', '07:55:20', '08:01:48']})

@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))

Output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM