Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nested dictionary key value with .get()

Tags:

With a simple dictionary like:

myDict = {'key1':1, 'key2':2} 

I can safely use:

print myDict.get('key3') 

and even while 'key3' is not existent no errors will be thrown since .get() still returns None.

Now how would I achieve the same simplicity with a nested keys dictionary:

myDict={} myDict['key1'] = {'attr1':1,'attr2':2} 

The following will give a KeyError:

print myDict.get('key1')['attr3'] 

This will go through:

print myDict.get('key1').get('attr3') 

but it will fail with adn AttributeError: 'NoneType' object has no attribute 'get':

print myDict.get('key3').get('attr1') 
like image 402
alphanumeric Avatar asked May 05 '14 01:05

alphanumeric


People also ask

How do you get a value from a nested dictionary?

Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).

How do you access nested dictionary in Python?

To access element of a nested dictionary, we use indexing [] syntax in Python.

How do you get a value from a dictionary key Python?

In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.


2 Answers

dict.get accepts additional default parameter. The value is returned instead of None if there's no such key.

print myDict.get('key1', {}).get('attr3') 
like image 147
falsetru Avatar answered Dec 04 '22 08:12

falsetru


There is a very nice blog post from Dan O'Huiginn on the topic of nested dictionaries. He ultimately suggest subclassing dict with a class that handles nesting better. Here is the subclass modified to handle your case trying to access keys of non-dict values:

class ndict(dict):      def __getitem__(self, key):          if key in self: return self.get(key)          return self.setdefault(key, ndict()) 

You can reference nested existing keys or ones that don't exist. You can safely use the bracket notation for access rather than .get(). If a key doesn't exist on a NestedDict object, you will get back an empty NestedDict object. The initialization is a little wordy, but if you need the functionality, it could work out for you. Here are some examples:

In [97]: x = ndict({'key1': ndict({'attr1':1, 'attr2':2})})  In [98]: x Out[98]: {'key1': {'attr1': 1, 'attr2': 2}}  In [99]: x['key1'] Out[99]: {'attr1': 1, 'attr2': 2}  In [100]: x['key1']['key2'] Out[100]: {}  In [101]: x['key2']['key2'] Out[101]: {}  In [102]: x['key1']['attr1'] Out[102]: 1 
like image 36
jxstanford Avatar answered Dec 04 '22 09:12

jxstanford