Reputation: 1109
I have this code below and I want to print the combo[values]
for any combo[keys]
in combo that are equal to numb[i]
numb = [5, 7, 49, 11, 13]
combo = {45 : (-1002,-1023), 49 : (-9999,-2347), 20 : (-1979, -1576), 13 : (-6000,-3450), 110 : (-2139, -8800), 7 : (-6754,-9087) }
How do I do it, please?
Upvotes: 0
Views: 997
Reputation: 1124070
You mean loop through numb
and print any key if present?
Two options; with a loop:
for key in numb:
if key in combo:
print combo[key]
which can be expressed as a list comprehension too, to produce a list:
[combo[key] for key in numb if key in combo]
Or with dictionary views:
for key in combo.viewkeys() & numb:
print combo[key]
again as a list comprehension too:
[combo[key] for key in combo.viewkeys() & numb]
Demo:
>>> numb = [5, 7, 49, 11, 13]
>>> combo = {45 : (-1002,-1023), 49 : (-9999,-2347), 20 : (-1979, -1576), 13 : (-6000,-3450), 110 : (-2139, -8800), 7 : (-6754,-9087) }
>>> [combo[key] for key in numb if key in combo]
[(-6754, -9087), (-9999, -2347), (-6000, -3450)]
>>> [combo[key] for key in combo.viewkeys() & numb]
[(-9999, -2347), (-6000, -3450), (-6754, -9087)]
What route you take depends on the size of combo
and numb
, and on whether numb
could be a set
as well. If numb
could be a set, the dict.viewkeys()
could optimize the intersection operation by using the smaller of the two and will most probably be the faster option, especially for larger datasets.
Upvotes: 5
Reputation: 20391
This can be done with a simple list comprehension:
>>> [v for k, v in combo.items() if k in numb]
[(-6754, -9087), (-6000, -3450), (-9999, -2347)]
I think that is what you meant?
Upvotes: 1