简体   繁体   English

从嵌套字典中检索单级的 Pythonic 方法

[英]Pythonic way to retrieve single level from nested dictionary

I am trying to retrieve a single level from a nested dictionary.我正在尝试从嵌套字典中检索单个级别。 So for instance, given the dictionary below, I would expect to see the following results for the first and second level.因此,例如,给定下面的字典,我希望看到第一级和第二级的以下结果。

nested_dict = {
  'foo':'bar',
  'baz':{
    'foo':'baz'
  }}

# level 0
{'foo':'bar'}

# level 1
{'foo':'baz'}

I can retrieve the first level using a dict comprehension:我可以使用dict理解检索第一级:

{k:v for (k,v) in nested_dict.items() if type(v) is not dict}
>>> {'foo':'bar'}

Or retrieve a specified level using a recursion:或使用递归检索指定级别:

def get_level(nested_dict, level):
  if level == 0:
    return {k:v for (k,v) in nested_dict.items() if type(v) is not dict}
  else:
    this_level = {}
    for (k,v) in nested_dict.items():
      if type(v) is dict:
        this_level.update(v)
    return get_level(this_level, level - 1)

get_level(nested_dict, 1)
>>> {'foo':'baz'}

I am now wondering if there is a more Pythonic/clean/out of the box way to retrieve the levels of nested dictionaries (as I already did above), if necessary with help of a package.我现在想知道是否有更 Pythonic/clean/out of the box 的方式来检索嵌套字典的级别(正如我在上面已经做过的那样),如果需要的话,在 package 的帮助下。

As stated in the comments, I'm assuming you don't have duplicates:如评论中所述,我假设您没有重复项:

nested_dict = {
  'foo':'bar',
  'baz':{
    'foo':'baz',
    'fee': {
        'foo': 'fee'
    }
  },
  'baz2':{
    'foo2':'baz2'
  }
  }

def get_level(dct, level):
    if level == 0:
        yield from ((k, v) for k, v in dct.items() if not isinstance(v, dict))
    else:
        yield from ((kk, vv) for v in dct.values() if isinstance(v, dict) for kk, vv in get_level(v, level-1))


print(dict(get_level(nested_dict, 1)))

Prints:印刷:

{'foo': 'baz', 'foo2': 'baz2'}

print(dict(get_level(nested_dict, 2)))

Prints:印刷:

{'foo': 'fee'}

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

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