python 获取所有子字典中的键

0 投票
3 回答
715 浏览
提问于 2025-04-17 22:18

在Python中,如果我有一个包含子字典的字典

d = {
    'a' : {
        'aa': {},
        'ab': {},
    },
    'b' : {
        'ba': {},
        'bb': {},
    }
}

我该如何获取每个子字典的键呢?

d.keys()
d['a'].keys()
d['b'].keys()

这是获取键的正常方法,但如果我有很多子字典,我该如何获取每个子字典的键呢?

编辑

我需要这些键来访问一个有五层或更多层的字典,

d[k1][k2][k3][k4][k5]

在某些情况下,我需要获取“k2”键下的信息,在其他情况下则需要“k3”键下的信息,等等。

3 个回答

0

这要看你的小字典里有没有字典。如果有的话,你可以写一个函数,通过递归的方式来检查这些类型。

def checksubtype(d):
  # d is a dictionary check the subtypes.
  for k in d:
    if type(d[k]) == type(d):
      print 'key', k, 'contains a dictionary'
      checktype(d[k])
    else:
      print 'key', k, 'has type', type(d[k])

>>> d = {'a': {'aa': [1, 2, 3], 'bb': [3, 4]}, 'b': {'ba': [5, 6], 'bb': [7, 8]}}
>>> checksubtype(d)
key a contains a dictionary
key aa has type <type 'list'>
key bb has type <type 'list'>
key b contains a dictionary
key ba has type <type 'list'>
key bb has type <type 'list'>

我用了直接检查类型的方法,而不是用isinstance,这样可以更清楚地说明我的意思。

2

这个解决方案适用于任意层级嵌套的字典

d = {
    'a' : {
        'aa': {},
        'ab': {},
    },
    'b' : {
        'ba': {},
        'bb': {},
    }
}

from itertools import chain
def rec(current_dict):
    children = []
    for k in current_dict:
        yield k
        if isinstance(current_dict[k], dict):
            children.append(rec(current_dict[k]))
    for k in chain.from_iterable(children):
        yield k

print list(rec(d))
# ['a', 'b', 'aa', 'ab', 'ba', 'bb']
6

如果你想获取所有层级的键,可以使用递归的方法:

def nested_keys(d):
    yield d.keys()
    for value in d.values():
        if isinstance(value, dict):
            for res in nested_keys(value):
                yield res

这是一个生成器函数,你可以循环输出的结果,或者用 list 来把它变成列表。这个方法会生成一系列的键,而不是单个的键。在Python 3中,这意味着你会得到字典的视图,比如说,空字典也会被包含在内:

>>> d = {
...     'a' : {
...         'aa': {},
...         'ab': {},
...     },
...     'b' : {
...         'ba': {},
...         'bb': {},
...     }
... }
>>> def nested_keys(d):
...     yield d.keys()
...     for value in d.values():
...         if isinstance(value, dict):
...             for res in nested_keys(value):
...                 yield res
... 
>>> for keys in nested_keys(d):
...     print keys
... 
['a', 'b']
['aa', 'ab']
[]
[]
['ba', 'bb']
[]
[]

不过,这样其实用处不大,因为你并不知道这些键是属于哪个字典的。

撰写回答