Python 比较两个字典键值并在匹配时返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13714982/
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 Two Dictionaries Key Values and Returning the Value If Match
提问by yrekkehs
I'm a beginner to Python, but I've been trying this syntax and I cannot figure it out -- which was been really baffling.
我是 Python 的初学者,但我一直在尝试这种语法,但我无法弄清楚——这真的很令人困惑。
crucial = {'eggs': '','ham': '','cheese': ''}
dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
if crucial.keys() in dishes.keys():
print dishes[value]
What I want to do is -- if crucial has a key (in this case, eggs) in the dishes, it will return 2. It seems simple enough, but I believe I must be messing some type of syntax somewhere. If someone could guide me a little, that would be greatly appreciated.
我想要做的是——如果关键在盘子里有一把钥匙(在这种情况下,eggs),它会返回2。这看起来很简单,但我相信我一定是在某处搞乱了某种类型的语法。如果有人能指导我一点,那将不胜感激。
The real dictionaries I'm comparing with is about 150 keys long, but I'm hoping this code is simple enough.
我比较的真正字典大约有 150 个键长,但我希望这段代码足够简单。
采纳答案by timc
You need to iterate over the keys in crucial and compare each one against the dishes keys. So a directly modified version of your code.
您需要迭代关键的键并将每个键与菜肴键进行比较。所以你的代码的直接修改版本。
for key in crucial.keys():
if key in dishes.keys():
print dishes[key]
It could be better stated as (no need to specify .keys):
可以更好地表述为(无需指定 .keys):
for key in crucial:
if key in dishes:
print dishes[key]
回答by Shawn Zhang
using list comprehension is good
使用列表理解很好
[ dishes[x] for x in crucial if dishes.has_key(x) ]
or ,as per gnibbler:
或者,根据 gnibbler:
[ dishes[x] for x in crucial if x in dishes ]
this expression will iterate crucial every key in crucial, if key in dishes, it will return the value of same key in dishes , finally, return a list of all match values.
该表达式将迭代关键中的每个键,如果键是菜肴,它将返回菜肴中相同键的值,最后,返回所有匹配值的列表。
or , you can use this way, (set (crucial) & set(dishes)) return common keys of both set, then iterate this set and return the values in dishes .
或者,你可以使用这种方式, (set (crucial) & set(dishes)) 返回两个集合的公共键,然后迭代这个集合并返回盘中的值。
[ dishes[x] for x in set (crucial) & set(dishes) ]
回答by kmad
has_key()has been removed in Python 3: http://docs.python.org/3.1/whatsnew/3.0.html#builtins
has_key()已在 Python 3 中删除:http: //docs.python.org/3.1/whatsnew/3.0.html#builtins
Instead, you can use:
相反,您可以使用:
[dishes[key] for key in crucial.keys() if key in dishes]
The method used here is called list comprehension. You can read about it here:
这里使用的方法称为列表理解。你可以在这里读到它:
http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
回答by vossad01
If you are not already familiar with Python's REPL (Read-Evaluate-Print-Loop -- that thing where you type in code, press enter and it immediately evaluates), that would be a good tool here.
如果您还不熟悉 Python 的 REPL(读取-评估-打印-循环——在您输入代码的地方,按 Enter 并立即计算),那么这将是一个很好的工具。
So lets start breaking down your code.
所以让我们开始分解你的代码。
crucial = {'eggs': '','ham': '','cheese': ''}
dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
Simple enough. Though I note you do not have any values in the crucialsdictionary. I am not sure if that is an abbreviation for you example or if you are simply only caring about the keys. If you are only caring about the keys, then I assume you are using a dictionary for the sake of ensuring uniqueness. In that case, you should check out the setdata structure.
足够简单。尽管我注意到您在crucials字典中没有任何值。我不确定这是否是您示例的缩写,或者您是否只是只关心密钥。如果您只关心键,那么我假设您使用字典是为了确保唯一性。在这种情况下,您应该检查set数据结构。
Example:
例子:
crutial = set(['cheese', 'eggs', 'ham'])
Continuing on we have
继续我们有
if crucial.keys() in dishes.keys():
here you are using the incomparison operator. Example:
在这里您使用的是in比较运算符。例子:
5 in [5, 4] #True
3 in [5, 4] #False
If we evaluate crucial.keys()and dishes.keys()we get
如果我们评估crucial.keys()并dishes.keys()得到
>>> crucial.keys()
['cheese', 'eggs', 'ham']
>>> dishes.keys()
['eggs', 'bacon', 'sausage', 'spam']
so during execution your code evaluates as
所以在执行过程中你的代码评估为
['cheese', 'eggs', 'ham'] in ['eggs', 'bacon', 'sausage', 'spam']
which returns Falsebecause the value ['eggs', 'bacon', 'sausage'](which is a list) is not in the list ['eggs', 'bacon', 'sausage', 'spam'](in fact there are no lists within that list, only strings).
它返回False是因为值['eggs', 'bacon', 'sausage'](它是一个列表)不在列表中['eggs', 'bacon', 'sausage', 'spam'](实际上该列表中没有列表,只有字符串)。
Thus you are evaluating as
因此,您正在评估为
if False:
print dishes[value] #note value is not defined.
It rather looks like you have mixed/confused the inoperator which returns a boolean and the for iterator (for item in collection). There is a syntax for this sort of thing. It is called list comprehensionswhich you can find samples of in @ShawnZhang and @kmad's answers. You can think of it as a terse way to filter and modify (map) a collection, returning a list as a result. I do not want to get too in-depth there or I will end up in an introduction to functional programming.
看起来您已经混合/混淆了in返回布尔值的运算符和 for 迭代器 ( for item in collection)。这种事情有一种语法。它被称为列表推导式,您可以在@ShawnZhang 和@kmad 的答案中找到示例。您可以将其视为过滤和修改(映射)集合的简洁方法,结果返回一个列表。我不想在那里太深入,否则我最终会介绍函数式编程。
Your other option is to use the for .. initeration and inoperators separately. This is the solution @timc gave. Such solutions are probably a more familiar or easier for beginners. It clearly separates the behavior of iterating and filtering. It is also more like what would be written in other programming languages that do not have an equivalent to list comprehensions. Those who work in Python a lot would probably favor the comprehension syntax.
您的另一个选择是单独使用for .. in迭代和in运算符。这是@timc 给出的解决方案。对于初学者来说,这样的解决方案可能更熟悉或更容易。它清楚地分离了迭代和过滤的行为。它也更像是用其他没有与列表推导式等效的编程语言编写的内容。那些经常使用 Python 的人可能会喜欢理解语法。
回答by Blckknght
If you're using Python 3, the keysmethod of dictionaries follows the setinterface. That means you can do an intersection of the keys of the two dictionaries using the &operator.
如果您使用的是 Python 3,则keys字典的方法遵循set接口。这意味着您可以使用&运算符对两个字典的键进行交集。
for key in crucial.keys() & dishes.keys():
print(dishes[key])
Or if you need a list of the values:
或者,如果您需要值列表:
result = [dishes[key] for key in crucial.keys() & dishes.keys()]
In Python 2 you could manage the same thing by explicitly creating sets (perhaps from the iterkeysgenerator), but probably it would be better to simply do a loop over the keys, like several of the other answer suggest.
在 Python 2 中,您可以通过显式创建集合(可能来自iterkeys生成器)来管理相同的事情,但可能最好简单地对键进行循环,就像其他几个答案所建议的那样。
Here's a variation on the loop that I don't think I've seen anyone else do. The outer loop gets both the keys and values from the dishesdict, so you don't need to separately look up the value by key.
这是循环的一个变化,我认为我没有见过其他人这样做。外循环从dishes字典中获取键和值,因此您不需要单独按键查找值。
for key, value in dishes.iteritems(): # use items() in Python 3
if key in crucial:
print value
回答by JoeLiu
crucial = {'eggs': '','ham': '','cheese': ''}
dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
for key in set(dishes.keys()) & set(crucial.keys()):
print dishes[key]
Similarly, you can have set(dishes.keys()) - set(crucial.keys()), set(dishes.keys()) | set(crucial.keys()), or set(dishes.keys()) ^ set(crucial.keys()).
同样,你可以有set(dishes.keys()) - set(crucial.keys()),set(dishes.keys()) | set(crucial.keys())或set(dishes.keys()) ^ set(crucial.keys())。

