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

2024-04-19 05:47:40 发布

您现在位置:Python中文网/ 问答频道 /正文

list1 = [123, 123, 123, 456]
list2 = ['word1', 'word2', 'word3', 'word4']

我希望输出是python字典

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

我在列表1中多次出现值,我想将列表2的所有值映射到列表1,而不需要重复键。你知道吗


Tags: 列表字典list2list1word1word2word3word4
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']}

可以使用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']

相关问题 更多 >