简体   繁体   中英

check if a value exists in dictionary python

I have something like, (which works fine and) gives me key and variables of values.

for k,v in x.iteritems():
        print k, v.samplekey,v.units,v.comment

where x is dictionary and v is netCDF4 variable . For dictionary 'v', there may or maynot exist a value for the keys. [eg key 'units' may exist in one of the items in dictionary while might be missing from others.]

I am getting AttributeError: Attribute not found . message when the key is not found in dictionary. I am trying to fill in N/A whenever no key isn't found.

Use the hasattr method:

def attr(x, a):
    return x.__getattribute__(a) if hasattr(x, a) else None

print k, attr(v, 'samplekey'), attr(v, 'units'), attr(v, 'comment')

Or alternatively, the getattr builtin (thanks RemcoGerlich!):

print k, getattr(v, 'samplekey', None)

Use getattr , which takes a default for when the attribute doesn't exist:

for k,v in x.iteritems():
    print (k,
           getattr(v, 'samplekey', 'N/A'),
           getattr(v, 'units', 'N/A'),
           getattr(v, 'comment', 'N/A'))

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