比较 Python 中的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/434353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing dictionaries in Python
提问by user44511
Given two dictionaries, d1
and d2
, and an integer l
, I want to find all keys k
in d1
such that either d2[k]<l
or k not in l
. I want to output the keys and the corresponding values in d2
, except if d2
does not contain the key, I want to print 0. For instance, if d1
is
给定两个字典,d1
并d2
和一个整数l
,我想找到所有的钥匙k
在d1
这样的,要么d2[k]<l
或k not in l
。我想输出中的键和对应的值d2
,除非d2
不包含键,我想打印0。例如,如果d1
是
a: 1
b: 1
c: 1
d: 1
and d2
is
并且d2
是
a: 90
b: 89
x: 45
d: 90
and l
is 90, the output would be (possibly in a different order)
并且l
是 90,输出将是(可能以不同的顺序)
b 89
c 0
What is the best way to do this in Python? I am just starting to learn the language, and so far this is what I have:
在 Python 中执行此操作的最佳方法是什么?我刚刚开始学习这门语言,到目前为止,这是我所拥有的:
for k in d1.keys():
if k not in d2:
print k, 0
else:
if d2[k]<l:
print k, d2[k]
This works of course (unless I have a typo), but it seems to me that there would be a more pythonic way of doing it.
这当然有效(除非我有错别字),但在我看来,会有一种更 Pythonic 的方式来做到这一点。
回答by dF.
Yours is actually fine -- you could simplify it to
你的其实很好——你可以把它简化为
for k in d1:
if d2.get(k, 0) < l:
print k, d2.get(k, 0)
which is (to me) pythonic, and is pretty much a direct "translation" into code of your description.
这是(对我来说)pythonic,并且几乎是直接“翻译”为您的描述代码。
If you want to avoid the double lookup, you could do
如果你想避免双重查找,你可以这样做
for k in d1:
val = d2.get(k, 0)
if val < l:
print k, val
回答by daniel
You can simplify this by using a defaultdict. Calling __getitem__ on a defaultdict will return the "default" value.
您可以使用 defaultdict 来简化此操作。在 defaultdict 上调用 __getitem__ 将返回“默认”值。
from collections import defaultdict
d = defaultdict(int)
print d['this key does not exist'] # will print 0
Another bit that you could change is not to call keys. The dictionary implements iter. It would be preferable to simply write:
您可以更改的另一点是不要调用键。字典实现了iter。最好简单地写:
for k in d1:
回答by Federico A. Ramponi
Here is a compact version, but yours is perfectly OK:
这是一个紧凑的版本,但你的完全没问题:
from collections import defaultdict
d1 = {'a': 1, 'b': 1, 'c': 1, 'd': 1}
d2 = {'a': 90, 'b': 89, 'x': 45, 'd': 90}
l = 90
# The default (==0) is a substitute for the condition "not in d2"
# As daniel suggested, it would be better if d2 itself was a defaultdict
d3 = defaultdict(int, d2)
print [ (k, d3[k]) for k in d1 if d3[k] < l ]
Output:
输出:
[('c', 0), ('b', 89)]