使用默认值的Python嵌套字典查找

时间:2020-12-16 18:12:29
>>> d2
{'egg': 3, 'ham': {'grill': 4, 'fry': 6, 'bake': 5}, 'spam': 2}
>>> d2.get('spamx',99)
99
>>> d2.get('ham')['fry']
6

I want to get value of fry inside of ham, if not, get value, 99 or 88 as the 2nd example. But how?

我想获得火腿里面的鱼苗值,如果没有,得到值,99或88作为第二个例子。但是怎么样?

4 个解决方案

#1


13  

d2.get('ham', {}).get('fry', 88)

I would probably break it down into several statements in real life.

我可能会把它分解成现实生活中的几个陈述。

ham = d2.get('ham', {})
fry = ham.get('fry', 88)

#2


3  

For the default values of get to work correctly the first default needs to be a dictionary, so that you can chain the .get calls correctly if the first fails.

对于get的正常工作的默认值,第一个默认值需要是字典,这样如果第一个失败,您可以正确链接.get调用。

d.get('ham',{}).get('fry',88)

you could also use a try, except block

你也可以使用try,除了块

def get_ham_fry()
  try:
    return d['ham']['fry']
  except AttributeError,e:
    return 88

#3


3  

If you need to do this a lot, you can write a helper function

如果你需要做很多事情,你可以写一个辅助函数

def get_nested(d, list_of_keys, default):
    for k in list_of_keys:
        if k not in d: 
            return default
        d=d[k]
    return d

print get_nested(d2,['ham','spam'],99)
print get_nested(d2,['ham','grill'],99)

#4


0  

Here's a solution for dealing with nested dictionaries:

这是处理嵌套字典的解决方案:

def get(root, *keys):
    """
    Returns root[k_1][k_2]...[k_n] if all k_1, ..., k_n are valid keys/indices. 
    Returns None otherwise
    """
    if not keys:
        return root
    if keys[0] not in root:
        return None
    if keys[0] in root:
        return get(root[keys[0]], *keys[1:])

Usage:

>>> d = {'a': 1, 'b': {'c': 3}}
>>> get(d, 'b', 'c')
3
>>> get(d. 'key that's not in d')
None
>>> get(d)
{'a': 1, 'b': {'c': 3}}

#1


13  

d2.get('ham', {}).get('fry', 88)

I would probably break it down into several statements in real life.

我可能会把它分解成现实生活中的几个陈述。

ham = d2.get('ham', {})
fry = ham.get('fry', 88)

#2


3  

For the default values of get to work correctly the first default needs to be a dictionary, so that you can chain the .get calls correctly if the first fails.

对于get的正常工作的默认值,第一个默认值需要是字典,这样如果第一个失败,您可以正确链接.get调用。

d.get('ham',{}).get('fry',88)

you could also use a try, except block

你也可以使用try,除了块

def get_ham_fry()
  try:
    return d['ham']['fry']
  except AttributeError,e:
    return 88

#3


3  

If you need to do this a lot, you can write a helper function

如果你需要做很多事情,你可以写一个辅助函数

def get_nested(d, list_of_keys, default):
    for k in list_of_keys:
        if k not in d: 
            return default
        d=d[k]
    return d

print get_nested(d2,['ham','spam'],99)
print get_nested(d2,['ham','grill'],99)

#4


0  

Here's a solution for dealing with nested dictionaries:

这是处理嵌套字典的解决方案:

def get(root, *keys):
    """
    Returns root[k_1][k_2]...[k_n] if all k_1, ..., k_n are valid keys/indices. 
    Returns None otherwise
    """
    if not keys:
        return root
    if keys[0] not in root:
        return None
    if keys[0] in root:
        return get(root[keys[0]], *keys[1:])

Usage:

>>> d = {'a': 1, 'b': {'c': 3}}
>>> get(d, 'b', 'c')
3
>>> get(d. 'key that's not in d')
None
>>> get(d)
{'a': 1, 'b': {'c': 3}}