我有两个大小相同的列表,我想将这两个列表转换成具有唯一键的字典[duplicate]

问题描述 投票:-3回答:2
list1 = [123, 123, 123, 456] list2 = ['word1', 'word2', 'word3', 'word4']
我希望输出为python字典,

d = {123 : ['word1', 'word2', 'word3'], 456 : 'word4'}

我在列表1中多次出现值,我想将list2的所有值映射到list1而不重复键。
python python-3.x dictionary
2个回答
1
投票
您可以使用collections和zip()方法。

import collections list1 = [123, 123, 123, 456] list2 = ['word1', 'word2', 'word3', 'word4'] dict_value = collections.defaultdict(list) for key, value in zip(list1, list2): dict_value[key].append(value) for i in dict_value: print('key', i, 'items', dict_value[i], sep = '\t')

输出:

key 123 items ['word1', 'word2', 'word3'] key 456 items ['word4']


2
投票
这是基于itertools的方法:

from itertools import groupby, islice list1 = [123, 123, 123, 456] list2 = iter(['word1', 'word2', 'word3', 'word4']) {k:list(islice(list2, len(list(v)))) for k,v in groupby(list1)} # {123: ['word1', 'word2', 'word3'], 456: ['word4']}

© www.soinside.com 2019 - 2024. All rights reserved.