CapnShanty
CapnShanty

Reputation: 559

Need to pull multiple values from python list comprehension?

I have a dictionary with tuple keys, like so:

(1111, 3454): 34.55555
(1123, 4665): 67.12
(1111, 9797): 5.09

I need to do a list comprehension that grabs the values for all entries with a matching first element. Problem is, I ALSO need that second value of the tuple...

interimlist = [v for k,v in mydict.items() if k[0]==item[0]]

Is what I've got right now for pulling the values if the first element of the tuple is correct (item is an iterator variable). I'd like the output to be a list of tuples of (value, second tuple number), so with the example points, would be the following output if item[0] is 1111:

[(34.55555, 3454), (5.09, 9797)]

Upvotes: 1

Views: 118

Answers (1)

wim
wim

Reputation: 362717

The dict is not stored with a good with a good structure here. All the keys/vals must be iterated in order to do one lookup, so it is O(n) retrieval.

You should do a once-off re-keying of the data, adding another level of nesting in the dict:

>>> d
{(1111, 3454): 34.55555, (1123, 4665): 67.12, (1111, 9797): 5.09}
>>> d_new = {}
>>> for (k1, k2), v in d.items():
...     if k1 not in d_new:
...         d_new[k1] = {}
...     d_new[k1][k2] = v

And now, O(1) lookups are restored:

>>> d_new[1111]
{3454: 34.55555, 9797: 5.09}
>>> [item[::-1] for item in d_new[1111].items()]
[(34.55555, 3454), (5.09, 9797)]

Upvotes: 1

Related Questions