Reputation: 2083
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:
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.
Upvotes: 3
Views: 1975
Reputation: 1
keys = ['a','b','c','d']
A = [1,2,3,4]
B = [9,2,1,2]
C = [4,1,2,3]
hu = dict(zip(keys,zip(A,B,C)))
hu
result:
{'a': (1, 9, 4), 'b': (2, 2, 1), 'c': (3, 1, 2), 'd': (4, 2, 3)}
hu['a'][0] --> 1
hu['a'][1] --> 9
Upvotes: -1
Reputation: 14094
This is one approach that doesn't require 2 for loops
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]}
Upvotes: 5
Reputation: 4391
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.
# 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.
Upvotes: -1
Reputation: 662
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 ;)
Upvotes: 0