【问题标题】:Check if a nested dictionary is a subset of another nested dictionary检查嵌套字典是否是另一个嵌套字典的子集
【发布时间】:2015-06-02 15:55:05
【问题描述】:

假设我有以下两个字典:

dict1 = 
{ 
   'battery1' : { 'Charge': 'enable', 'Discharge': 'enable' },
   'battery2' : { 'Charge': 'enable', 'Discharge': 'enable' }
}

dict2 = 
{
   'Estimated battery run-time': '05:00 minutes', 

   'battery1': {'Device': 'controller', 'Discharge': 'enable', 
   'Charging State': 'Fully charged', 'Charge': 'disable'}, 

   'battery2': {'Device': 'controller', 'Discharge': 'enable', 
   'Charging State': 'Fully charged', 'Charge': 'disable'}
}

我想检查 dict1 是否是 dict2 的子集(即 dict2 中的键值对是否显示在 dict2 中,而 dict2 中的相同键将包含额外值,如充电状态和设备)。

for k, v in dict1.iteritems():
    for t, c in v.iteritems():
        if k in dict2:
            if c != dict2[k][v]:
                mismatch = true
                break;

但我明白了

unhashable type: 'dict' error. 

请注意,这是一个不同的问题:

Loop through all nested dictionary values?

Taking sums of nested values of nested dictionary

Iterate over nested dictionary

有人可以帮忙吗?

提前致谢。

【问题讨论】:

  • 你需要和dict2[k][t]比较,你也需要使用mismatch = True
  • 这里不完全清楚你想要什么,你能扩展你期望的输出

标签: python dictionary


【解决方案1】:

您有一些错误。如果我了解您的需求,那么这对我有用。这是python 3版本。对于 python 2,将 dict.items() 替换为 dict.iteritems()。

def compare(dict1, dict2):
    for k1, v1 in dict1.items():
        if k1 in dict2:
            for k2, v2 in v1.items():
                if v2 != dict2[k1][k2]:
                    return False
    return True

例如,使用这些数据

dict1 = {
   'battery1' : { 'Charge': 'enable', 'Discharge': 'enable' },
   'battery2' : { 'Charge': 'enable', 'Discharge': 'enable' }
}

dict2a = {
    'Estimated battery run-time': '05:00 minutes',
    'battery1': {
        'Device': 'controller',
        'Discharge': 'enable',
        'Charging State': 'Fully charged',
        'Charge': 'enable'
    },
    'battery2': {
        'Device': 'controller',
        'Discharge': 'enable',
        'Charging State': 'Fully charged',
        'Charge': 'enable'
    }
}

dict2b = {
    'Estimated battery run-time': '05:00 minutes',
    'battery1': {
        'Device': 'controller',
        'Discharge': 'enable',
        'Charging State': 'Fully charged',
        'Charge': 'disable'
    },
    'battery2': {
        'Device': 'controller',
        'Discharge': 'enable',
        'Charging State': 'Fully charged',
        'Charge': 'disable'
    }
}

为每个字典运行它会产生正确的答案(我认为)。

print(compare(dict1, dict2a)) # True
print(compare(dict1, dict2b)) # False

【讨论】:

  • 为什么这个被否决了?该解决方案有效并且符合 OP 的要求。
  • 顺便说一句,这里有一个潜在的缺陷,即 dict1 中不存在于 dict2 中的键永远不会被比较,这使得 dict1 不是真正的 dict2 的子集。通过将 else: return False 添加到 if k1 in dict2 测试来解决此问题。
【解决方案2】:

我有理由比较部分嵌套的字典和列表并想出了这个:

def compare_partial_nested_data(small, big):
    for skey in small:
        found = False
        for bkey in big:
            bval, sval = bkey, skey # list values are the keys
            if isinstance(small, dict) and isinstance(big, dict):
                bval, sval = big[bkey], small[skey] # replace values if dict
            if isinstance(sval, (dict, list)) and isinstance(bval, (dict, list)):
                found = compare_partial_nested_data(sval, bval)
            else:
                found = skey==bkey and sval==bval
            if found: break
        if not found: return False
    return True

测试:

find = {
    'zzz': [{'ccc': [{'ccc': 'ccc'}, 12345]}, 'abcde'],
    'xxx': 'xxx',
}
message = {
    'xxx': 'xxx',
    'yyy': 'yyy',
    'zzz': [
        {'aaa': 'aaa'},
        {'bbb': 'bbb'},
        {'ccc': [
            {'aaa': 'aaa'},
            {'bbb': 'bbb'},
            {'ccc': 'ccc'},
            12345,
        ]},
        {},
        [],
        67890,
        'abcde',
    ]
}
print(compare_partial_nested_dicts(find, message))
> True

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    相关资源
    最近更新 更多