检查Python字典是否具有相同的形状和键 [英] Check that Python dicts have same shape and keys
问题描述
对于像 x = {'a':1,'b':2}
这样的单层dict,问题很简单,可以通过SO(
For single layer dicts like x = {'a': 1, 'b': 2}
the problem is easy and answered on SO (Pythonic way to check if two dictionaries have the identical set of keys?) but what about nested dicts?
例如, y = {'a':{'c':3},'b':{'d':4}}
具有键'a'
和'b'
,但我想将其形状与另一个嵌套的dict结构进行比较,例如 z = {'a':{'c':5},'b':{'d':6}}
与 y
具有相同的形状和键(可以使用不同的值). w = {'a':{'c':3},'b':{'e':4}}
将具有键'a'
和'b'
,但在下一层不同于 y
,因为 w ['b']
具有键'e'
,而 y ['b']
具有键'd'
.
For example, y = {'a': {'c': 3}, 'b': {'d': 4}}
has keys 'a'
and 'b'
but I want to compare its shape to another nested dict structure like z = {'a': {'c': 5}, 'b': {'d': 6}}
which has the same shape and keys (different values is fine) as y
. w = {'a': {'c': 3}, 'b': {'e': 4}}
would have keys 'a'
and 'b'
but on the next layer in it differs from y
because w['b']
has key 'e'
while y['b']
has key 'd'
.
想要两个参数 dict_1
和 dict_2
的简短函数,如果它们具有与上述相同的形状和键,则返回 True
,否则为 False
.
Want a short/simple function of two arguments dict_1
and dict_2
and return True
if they have same shape and key as described above, and False
otherwise.
推荐答案
这提供了两个字典的副本,这些字典都去除了任何非字典值,然后将它们进行比较:
This provides a copy of both dictionaries stripped of any non-dictionary values, then compares them:
def getshape(d):
if isinstance(d, dict):
return {k:getshape(d[k]) for k in d}
else:
# Replace all non-dict values with None.
return None
def shape_equal(d1, d2):
return getshape(d1) == getshape(d2)
这篇关于检查Python字典是否具有相同的形状和键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!