我有两个词典,如下所示。我想要做的是检查a
字典中是否包含所有b
的值。两个词典可能是不同的结构。某些a
的密钥未包含在b
中。我想知道实现这一点的通用方法。
检查值列表。所有a
的值都应包含在b
预期输出类似于文本输出。我知道a[0].name
在python中无效。这不是python的原始代码。
a[0]['name']
中b
? =>是的,相同的价值a[0]['vals'][0]['apple']
中b
? =>是的,但价值不同a[0]['vals'][0]['banana'][0]['hoge']
中b
? =>不存在a[0]]'vals'][0]['banana'][0]['fuga']
中b
? =>不退出两本词典。
a = [
{
"name":"hoge",
"vals":[
{
"apple":11,
"banana":{
"hoge":1,
"fuga":"aaa"
}
}
]
}
]
b = [
{
"name":"hoge",
"vals":[
{
"apple":21,
"grape":{
"foo":1
}
}
]
}
]
答案 0 :(得分:2)
您可以像我在下面那样实现dict
比较功能:
def compare_ndic(src, dst, pre=''):
for skey, sval in src.items():
if pre:
print_skey = pre + '.' + skey
else:
print_skey = skey
if skey not in dst.keys():
print('Key "{}" in {} does not existed in {}'.format(print_skey, 'src', 'dst'))
else:
if isinstance(sval, dict) and isinstance(dst.get(skey), dict):
#If the value of the same key is still dict
compare_ndic(sval, dst.get(skey), print_skey)
elif sval == dst.get(skey):
print('Value of key "{}" in {} is the same with value in {}'.format(print_skey, 'src', 'dst'))
else:
print('Value of key "{}" in {} is different with value in {}'.format(print_skey, 'src', 'dst'))
a = {
"name":"hoge",
"vals":
{
"apple":11,
"banana":{
"hoge":1,
"fuga":"aaa"
}
}
}
b = {
"name": "hoge",
"vals":
{
"apple": 11,
"banana": {
"hoge": 2,
"fuga": "aaa",
}
}
}
compare_ndic(a, b)
输出如下:
Value of key "vals.banana.fuga" in src is the same with value in dst
Value of key "vals.banana.hoge" in src is different with value in dst
Value of key "vals.apple" in src is the same with value in dst
Value of key "name" in src is the same with value in dst
请注意,我的代码不能直接用于您的方案,因为您的数据中包含list
。您可以添加一些条件语句,并在必要时迭代整个列表。无论如何,我只提供了一个比较两个词的想法,你需要以自己的方式修改它。
答案 1 :(得分:-1)
您在访问方法时出错。 a是作为
访问的列表a[0]
但是[0]是以
的形式访问的字典a[0]['vals'] # 'vals' is a key stored in dictionary
只知道你可以尝试的词典中的键
a[0].keys() # gives you result dict_keys(['name', 'vals']) which you can iterate further as you wish
你可以使用
获得所有元素a[0].items() # gives you dict_items([('name', 'hoge'), ('vals', [{'banana': {'hoge': 1, 'fuga': 'aaa'}, 'apple': 21}])])
此外,在代码中使用正确的语法。 您在代码中使用了错误的语法
a = [{"name": "hoge", "vals": [{"apple": 21, "banana": {"hoge": 1, "fuga": "aaa"}}]}]
b = [{"name": "hoge", "vals": [{ "apple": 21, "grape": {"foo": 1}}]}]
if a[0]['name'] in b[0]['name']:
print('first match')
if a[0]['name'] == b[0]['name']:
print('item exist with same value')
else:
print('item exist but not same value')
for key in a[0]['vals'][0].keys():
if key in b[0]['vals'][0].keys():
print('second match with key : ' + str(key))
if a[0]['vals'][0][str(key)] == b[0]['vals'][0][str(key)]:
print('match exist with same value for key : ' + str(key))
else:
print('match failed for key : ' + str(key))
else:
print('match failed at 1')