简体   繁体   English

来自两个列表的字典,包括键的多个值

[英]Dict from two lists including multiple values for keys

Is there a possibility to create a dict from two lists with same key occurring multiple times without iterating over the whole dataset? 是否可以从两个具有相同键的列表中创建一个字典, 而不重复整个数据集?

Minimal example: 最小示例:

keys = [1, 2, 3, 2, 3, 4, 5, 1]
values = [1, 2, 3, 4, 5, 6, 7, 8]

# hoped for result:
dictionary = dict(???)
dictionary = {1 : [1,8], 2:[2,4], 3:[3,5], 4:[6], 5:[7]}

When using zip the key-value-pair is inserted overwriting the old one: 使用zip ,插入的键值对将覆盖旧的键值对:

dictionary = dict(zip(keys,values))
dictionary = {1: 8, 2: 4, 3: 5, 4: 6, 5: 7}

I would be happy with a Multidict as well. 我对Multidict也很满意。

This is one approach that doesn't require 2 for loops 这是一种不需要2 for循环的方法

h = defaultdict(list)
for k, v in zip(keys, values):
    h[k].append(v)

print(h)
# defaultdict(<class 'list'>, {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]})

print(dict(h))
# {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]}


This is the only one-liner I could do. 这是我唯一能做的。

dictionary = {k: [values[i] for i in [j for j, x in enumerate(keys) if x == k]] for k in set(keys)}

It is far from readable. 它远非易读。 Remember that clear code is always better than pseudo-clever code ;) 请记住,清晰的代码总是比伪智能代码更好;)

Here is an example that I think is easy to follow logically. 我认为这是一个易于理解的示例。 Unfortunately it does not use zip like you would prefer, nor does it avoid iterating, because a task like this has to involve iterating In some form. 不幸的是,它没有像您希望的那样使用zip ,也没有避免迭代,因为这样的任务必须涉及某种形式的迭代。

# Your data
keys = [1, 2, 3, 2, 3, 4, 5, 1]
values = [1, 2, 3, 4, 5, 6, 7, 8]

# Make result dict
result = {}
for x in range(1, max(keys)+1):
    result[x] = []

# Populate result dict
for index, num in enumerate(keys):
    result[num].append(values[index])

# Print result
print(result)

If you know the range of values in the keys array, you could make this faster by providing the results dictionary as a literal with integer keys and empty list values. 如果您知道keys数组中值的范围,则可以通过将results字典作为带有整数键和空列表值的文字提供, results加快此过程。

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

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