简体   繁体   中英

Printing the values of a dictionary when its key is equal to the value of a list element

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?

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM