Skip to content
Advertisement

Passing dictionary values to a function, with missing keys

I have a class with a constructor that receives several arguments. These arguments I get from an external file, which is a list of dictionaries.

My problem is that some dictionaries have missing fields. If a field is missing, I want the constructor to simply receive None instead. But as the code is written now, it exits on an exception.

This is a simple illustration of the situation

JavaScript

As the code is written right now, I get an exception that 'gender' does not exist as a key in the dictionary, which is true. I want any missing field to gets passed a None value, but without doing a billion ifs or try .. excepts. Is there a good way to do this? Obviously without still incurring an exception.

Advertisement

Answer

In general, you can get a value from a dict with a default if it doesn’t exist with:

JavaScript

But in your case, this would be more appropriate:

JavaScript

Of course, this only works if the keys of the dictionaries match the names of the parameters exactly.

The ** operator ‘unpacks’ the dictionary, so this:

JavaScript

Is the same as:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement