从两个层次的字典中获得价值 [英] Get value from dictionary two levels deep

查看:97
本文介绍了从两个层次的字典中获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当使用Python存在两个级别的键时,才可以用一种优雅的方法来获取字典中子键的值?

What is an elegant way of getting the value for a sub-key inside a dictionary, but only if the two levels of keys exist using python?

例如,我想从爸爸"那里获得团队"的价值.因此,如果爸爸不存在,它应该不返回任何值,否则继续寻找子项"team",如果不存在,则不返回任何值,否则返回该值.

For example I want to get the value for 'team' from 'dad'. So if Dad doesn't exist it should return none, otherwise continue to look for subkey 'team' and if that doesn't exist return none, otherwise return the value.

有一种简单的方法可以编写一个递归函数,我只传递一个名称数组,然后通过它查找,如果击中缺少的键,它将返回一个定义的默认值.

Would there be an easy way to possibly write a recursive function which i just pass an array of names which it then looks through and if it hits a missing key it just returns a defined default value.

我知道我目前可以做

dict.get('dad', None)

我希望能够做这样的事情

I'd like to be able to do something like this

dict.get(['dad','team'], None)

dict

{  
   "dad":{  
      "team":"packers"
   },
   "mom":{  
      "show":"rugrats",
      "vehicle":"buggy"
   }
}

推荐答案

dict.get('dad', {}).get('team', None)

这恰好有两个层次.在一般情况下,您可以

That does exactly two levels. In the general case, you could

def recurGet(d, ks): 
  head, *tail = ks 
  return recurGet(d.get(head, {}), tail) if tail else d.get(head)

head, *tail = ks是Python3.在Python 2中,您必须明确将其编写为

The head, *tail = ks is Python 3. In Python 2, you would have to write it explicitly as

  head = ks[0]
  tail = ks[1:]

这篇关于从两个层次的字典中获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆