0

In python 2.7 I've got a dictionary of dictionaries, and I'm trying to get values from this in a speedy way. However, sometimes one of the keys (could be either one) doesn't exist in my dictionary, in that case I would like to get a default value.

My dictionary looks like this:

values = { '1A' : { '2A' : 'valAA', '2B' : 'valAB'},
           '1B' : { '2A' : 'valBA', '2B' : 'valBB'} }

which works great when I query it with existing keys:

>>> values['1A']['2A']
'valAA'
>>> values.get('1B').get('2B')
'valBB'

How do I get it to do this:

>>> values.get('not a key').get('not a key')
'not present'
Swier
  • 4,047
  • 3
  • 28
  • 52

2 Answers2

1

This works like a charm:

values.get(key1, {}).get(key2, defaultValue)

In case the second key is not present in the dictionary, the default value of the second .get() is returned. In case the first key is not present in the dictionary, the default value is an empty dictionary, which ensures the second key will not be present in it. The default value for the second .get() will then be returned as well.

For example:

>>> defaultValue = 'these are not the values you are looking for'
>>> key1, key2 = '1C', '2C'
>>> values.get(key1, {}).get(key2, defaultValue)
'these are not the values you are looking for'
>>> key1, key2 = '1A', '2B'
>>> values.get(key1, {}).get(key2, defaultValue)
'valAB'
Swier
  • 4,047
  • 3
  • 28
  • 52
1

Create a function to the get the value.

values = { '1A' : { '2A' : 'valAA', '2B' : 'valAB'},
           '1B' : { '2A' : 'valBA', '2B' : 'valBB'} }

def get_value(dict, k1, k2):
    try:
        return dict[k1][k2]
    except KeyError as ex:
        return 'does not exist'

print get_value(values, '1A', '2A')
print get_value(values, '1A', '4A')
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33