如何比较两个字典?
我正在输入一个字典,可能像这样:
myWorld = {'MH': {'Mumbai': 1, 'Pune': 2}, 'GUJ': 3, 'RSA': {} }
而我的测试字典是:
World = {'MH': {'Mumbai': 1, 'Pune': 2}, 'GUJ': 3, 'RSA': {}, 'USA': 4, 'UK': 5 }
我想检查一个条件,就是如果我在 myWorld
中输入的任何东西不在 World
中,就应该打印 NotFound
for key, val in myWorld.iteritems():
if (key, val) not in (World.keys(), World.values()) in World.iteritems():
print "NotFound"
else:
print "Correct"
不过,这似乎不是正确的方法。因为无论我输入什么字典,即使是 "{'RSA':{}}"
,我都得到了 NotFound
。我对 Python 还很陌生,所以不太了解。有人能告诉我哪里出错了,以及如何修复吗?
Dictionaries =
{
'A':{}, 'B':{}, 'C':{}, 'D':{}, 'myWorld' : {'id':1, 'name': 10},
{'id':2, 'name': 20},
{'id':3, 'name': 30},
{'id':4, 'name': 40},
{'id':5, 'name': 50}
}
我正在运行 tests
和 classes
。
A, B, C, D, myWorld
在这里是 classes
。
我像这样运行我的测试 mytest.py "{'A':{}}"
mytest.py "{'myWorld' : {'id':1, 'name': 10}}"
或者
mytest.py "{'myWorld' : {'id':2, 'name': 20}}"
所以我在 mytest.py
中输入的参数,我把它保存在 l 中。
其中 l = ast.literal_eval(args[0])
现在,当我不想运行不必要的测试时,我这样做:
if all(key in Dictionaries and Dictionaries[key] == key and value for key, value in l.iteritems()):
proceed
else:
exit(1)
现在根据这里给出的 if 语句的建议,它总是变为真,我在键和值组合错误的情况下总是继续。
例如,即使我输入 mytest.py 'myWorld' : {'id':1, 'name': 12}
我不想这样。我希望它只对 Dictionaries
中提到的可能性进行运行。
4 个回答
你还可以用这些方法来比较字典:
notthesame_item = set(myWorld.items()) ^ set(World.items())
print len(notthesame_item) # should be 0
XOR运算符(^)会把两个字典中相同的元素都去掉。
thesame_items = set(myWorld.items()) & set(World.items())
print len(thesame_items)
两个字典中匹配的元素会被显示出来。
原则上,这段代码应该能实现你想要的效果:
world_items = world.items()
if all(it in world_items for it in myWorld.iteritems()):
print 'correct'
else:
print 'not correct'
myWorld == World
if myWorld == World:
print 'correct'
else:
print 'not found'
这样做是可以的。
更新:
一种方法:
if all(key in World and World[key] == value for key, value in myWorld.iteritems()):
print "Correct"
else:
print "NotFound"
这个方法是通过简单的相等比较来判断值。如果你需要对比如说你里面的 'Mumbai'
字典做不同的处理,其实也不难,只需要改变你比较 value
的方式就可以了。