简体   繁体   English

如何在 Python 字典中获取内键

[英]How to get inner key in Python dictionary

Am I able to get the inner value by key due to some function like get.由于 get 之类的功能,我是否能够按键获取内部值? Simple dict:简单的字典:

dict1 = {
    'key1': 'asdfasdf'
}

If I want to get the value by key1 I just write dict1.get('key1') But what if I have such dict:如果我想通过key1获取值我只写dict1.get('key1')但是如果我有这样的字典怎么办:

dict2 = {
    'some_key': {
        'key1': 'asdfasdf'
    }
}

How can I get value by key1 like dict2.get('key1')?我怎样才能像 dict2.get('key1') 这样通过key1获取值?

As you can understand I just need these both types of dictionaries, so I don't need dict2['some_key']['key1']如您所知,我只需要这两种类型的词典,所以我不需要dict2['some_key']['key1']

That's a nested Dictionary那是一个嵌套的字典

you can use iterated comprehension if you want to avoid using keys of top level dictionary to access inner items如果你想避免使用顶级字典的键来访问内部项目,你可以使用迭代理解

eg例如

[x.get('key1') for x, x in dict2.items()]

or using just values或仅使用值

[x.get('key1') for x in x.values()]

this will return a list of asdfasdf这将返回 asdfasdf 列表

If you're looking for the value associated with the first occurrence of 'key1' in a nested dictionary, a little bit of recursion can get you there.如果您正在查找与嵌套字典中第一次出现的“key1”相关联的值,则可以通过一点递归来实现。

def first(d, k):
  if k in d: return d[k]
  for v in d.values():
    if isinstance(v, dict): 
      v2 = first(v, k)
      if v2: return v2

Consider:考虑:

>>> first({'a':{'b':42, 'c':27, 'd':{'e': 3.14, 'key1':'hello world'}}}, 'key1')
'hello world'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM