python - Printing the values of a dictionary when its key is equal to the value of a list element -
i have code below , want print combo[values]
combo[keys]
in combo equal 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 it, please?
you mean loop through numb
, print key if present?
two options; loop:
for key in numb: if key in combo: print combo[key]
which can expressed list comprehension too, produce list:
[combo[key] key in numb if key in combo]
or dictionary views:
for key in combo.viewkeys() & numb: print combo[key]
again list comprehension too:
[combo[key] 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] key in numb if key in combo] [(-6754, -9087), (-9999, -2347), (-6000, -3450)] >>> [combo[key] key in combo.viewkeys() & numb] [(-9999, -2347), (-6000, -3450), (-6754, -9087)]
what route take depends on size of combo
, numb
, , on whether numb
set
well. if numb
set, dict.viewkeys()
optimize intersection operation using smaller of 2 , faster option, larger datasets.
Comments
Post a Comment