Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a strange result when comparing 2 dictionaries in python

So I have a pair of dictionaries in python: (both have exactly the same keys)

defaults = {'ToAlpha': 4, 'ToRed': 4, 'ToGreen': 4, 'ToBlue': 4,}

bridged = {'ToAlpha': 3, 'ToRed': 0, 'ToGreen': 1, 'ToBlue': 2,}

When I iterate through one of the dictionaries I do a quick check to see if the other dict has the same key, if it does then print it.

for key, value in defaults.iteritems():
    if bridged.get(key):
        print key

What I would expect to see is:

ToAlpha
ToRed
ToGreen
ToBlue

But for some reason, 'ToRed' is not printed. I must be missing something really simple here, but have no idea might might be causing this.

bridged.get('ToRed')

and

defaults.get('ToRed')

both work independently, but when iterated through the loop... Nothing!

Any idea's?

like image 670
iGwok Avatar asked Sep 17 '26 01:09

iGwok


1 Answers

0 is false. Use in to check for containment.

if key in bridged:
like image 59
Ignacio Vazquez-Abrams Avatar answered Sep 20 '26 12:09

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!