【问题标题】:Python dict of dicts with default value [duplicate]具有默认值的字典的Python字典[重复]
【发布时间】:2016-06-25 11:19:17
【问题描述】:

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

【问题讨论】:

  • 对不起,错过了那个,我以为我发现了一些新东西,但它是重复的

标签: python python-2.7 dictionary default-value


【解决方案1】:

创建一个函数来获取值。

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

【讨论】:

  • 感谢您的建议
【解决方案2】:

这就像一个魅力:

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'

【讨论】:

  • 如果你先尝试 key2 这将不起作用
  • @RafaelCardoso:你为什么要先尝试 key2?这工作得很好。
  • @MartijnPieters 我看到不能保证你知道哪个键先出现。也许在这个键是“有序”的特定示例中,但这肯定不是通用解决方案。
  • @RafaelCardoso: 但key1 应用于外部字典,key2 应用于内部。这里有一个命令。我不确定你在说什么。
  • 我刚刚又读了一遍,你是对的。不知道我是从哪里弄来的,哈哈
猜你喜欢
  • 2021-07-27
  • 2017-09-06
  • 2017-01-27
  • 2016-01-28
  • 2011-05-04
  • 2011-06-29
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
相关资源
最近更新 更多