Skip to content
Advertisement

Adding Multiple Values to Single Key in Python Dictionary Comprehension

I wanted to learn how to use dictionary comprehension and decided to use one for the previously solved task. I need to assign multiple values to the same key. I was wondering if there’s a better way to achieve what I’m trying to do than with the code I’ve written so far.

graph = {(x1,y1): [(c,d) for a,b,c,d in data if a == x1 and b == y1] for x1 ,y1, x2, y2 in data}

For example I have this:

data = {(1,2,1,5),(1,2,7,2),(1,5,4,7),(4,7,7,5)}

The first two values should create a key and the remaining two should be added as a value of a key. With the given example I would like to return:

{(1, 2): [(1, 5), (7, 2)], (1, 5): [(4, 7)], (4, 7): [(7, 5)]}

Is there an easier way to do it than iterate through the entire data just to find the matching values?

Advertisement

Answer

Using this dict comprehension isn’t an efficient way here. It loops over the same input data repeatedly.

It’s more Pythonic to just use a simple for loop, iterating the data only once:

from collections import defaultdict

data = {(1,2,1,5),(1,2,7,2),(1,5,4,7),(4,7,7,5)}
output = defaultdict(list)

for a, b, c, d in data:
    output[a, b].append((c, d))
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement