Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from Python dict if key might not be present

Tags:

python

json

I am very new to Python and parsing data.

I can pull an external JSON feed into a Python dictionary and iterate over the dictionary.

for r in results:      print r['key_name'] 

As I walk through the results returned, I am getting an error when a key does not have a value (a value may not always exist for a record). If I print the results, it shows as

'key_name': None, 'next_key':................. 

My code breaks on the error. How can I control for a key not having a value?

Any help will be greatly appreciated!

Brock

like image 723
Btibert3 Avatar asked Feb 15 '10 02:02

Btibert3


People also ask

What does Python dictionary get return if key not found?

get() method returns: the value for the specified key if key is in the dictionary. None if the key is not found and value is not specified.

How do you check if a key is not present in a dictionary in Python?

Checking if key exists using the get() method The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.

What does dictionary get return if key not found?

If given key does not exists in dictionary, then it returns the passed default value argument. If given key does not exists in dictionary and Default value is also not provided, then it returns None.

How do you add a key to a dictionary Python if not exists?

Method 1: Add new keys using the Subscript notation This method will create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it will be added and will point to that value.


1 Answers

The preferred way, when applicable:

for r in results:      print r.get('key_name') 

this will simply print None if key_name is not a key in the dictionary. You can also have a different default value, just pass it as the second argument:

for r in results:      print r.get('key_name', 'Missing: key_name') 

If you want to do something different than using a default value (say, skip the printing completely when the key is absent), then you need a bit more structure, i.e., either:

for r in results:     if 'key_name' in r:         print r['key_name'] 

or

for r in results:     try: print r['key_name']     except KeyError: pass 

the second one can be faster (if it's reasonably rare than a key is missing), but the first one appears to be more natural for many people.

like image 98
Alex Martelli Avatar answered Sep 29 '22 06:09

Alex Martelli