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

时间:2020-06-15 09:29:15

标签: python dictionary

我有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']}

2 个答案:

答案 0 :(得分:1)

尝试一下,set e_pat = `zgrep "count" $file | cut -d'=' -f 2` if [$e_pat -gt 10000] then echo "Greater" else echo "lesser" fi 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)

答案 1 :(得分:1)

@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']}