[英]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.