Python 具有默认值的字典

Python dict of dicts with default value

在 python 2.7 中,我有一本字典,我正试图从中快速获取值。但是,有时我的字典中不存在其中一个键(可能是其中一个),在这种情况下我想获得一个默认值。

我的字典是这样的:

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

当我使用现有键查询时效果很好:

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

我怎样才能做到这一点:

>>> values.get('not a key').get('not a key')
'not present'

这很有魅力:

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

如果字典中不存在第二个键,则返回第二个 .get() 的默认值。 如果字典中不存在第一个键,则默认值为空字典,以确保其中不存在第二个键。第二个 .get() 的默认值也将返回。

例如:

>>> 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'

创建一个函数来获取值。

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')