比较两个字典键值并返回匹配的值

时间:2021-04-25 22:46:32

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.

我想做的是——如果至关重要的菜里有一把钥匙(在这个例子中是鸡蛋),它会返回2。这看起来很简单,但我相信我一定是把某种语法搞混了。如果有人能给我指点一下,我将不胜感激。

The real dictionaries I'm comparing with is about 150 keys long, but I'm hoping this code is simple enough.

我比较的真正的字典大约有150个键长,但是我希望这个代码足够简单。

6 个解决方案

#1


11  

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]

#2


2  

If you're using Python 3, the keys method of dictionaries follows the set interface. That means you can do an intersection of the keys of the two dictionaries using the & operator.

如果您使用的是Python 3,那么字典的键方法是遵循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 iterkeys generator), 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 dishes dict, so you don't need to separately look up the value by key.

这里有一个循环的变化,我想我没见过其他人这么做。外部循环从dish dict来获取键和值,因此不需要按键分别查找值。

for key, value in dishes.iteritems(): # use items() in Python 3
    if key in crucial:
        print value

#3


1  

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 (critical)和set(dish))返回两个set的公共键,然后迭代这个集合并返回dish中的值。

[ dishes[x] for x in set (crucial) & set(dishes) ]

#4


0  

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 crucials dictionary. 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 set data structure.

很简单。虽然我注意到你在十字架字典里没有任何值。我不确定这是你的例子的缩写,还是你只关心键。如果您只关心键,那么我假设您使用字典是为了确保惟一性。在这种情况下,应该检查set数据结构。

Example:

例子:

crutial = set(['cheese', 'eggs', 'ham'])

Continuing on we have

继续我们的

if crucial.keys() in dishes.keys():

here you are using the in comparison operator. Example:

这里使用的是in comparison运算符。例子:

5 in [5, 4] #True
3 in [5, 4] #False

If we evaluate crucial.keys() and dishes.keys() we get

如果我们评估cruci. keys()和洗碗机。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 False because 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,因为“鸡蛋”、“培根”、“香肠”(是一个列表)不在列表中(“鸡蛋”、“培根”、“香肠”、“垃圾邮件”)(实际上列表中没有列表,只有字符串)。

Thus you are evaluating as

因此,您正在评估as。

if False:
    print dishes[value] #note value is not defined.

It rather looks like you have mixed/confused the in operator 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 comprehensions which 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迭代器(用于集合中的项)。这类东西有一个语法。它被称为列表综合,你可以在@ShawnZhang和@kmad的答案中找到样本。您可以将它视为筛选和修改(映射)集合的一种简洁的方式,从而返回一个列表。我不想讲得太深入,否则我将在函数式编程的介绍中结束。

Your other option is to use the for .. in iteration and in operators 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 .. .分别在迭代和运算符中。这是@timc给出的解决方案。对于初学者来说,这样的解决方案可能更熟悉或更容易。它清楚地分离了迭代和过滤的行为。它也更像是用其他编程语言编写的,而这些语言并不具有列表理解。那些在Python中工作的人可能更喜欢理解语法。

#5


0  

has_key() has been removed in Python 3: http://docs.python.org/3.1/whatsnew/3.0.html#builtins

在Python 3中已经删除了has_key(): 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列表理解

#6


-1  

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()).

类似地,您可以设定(dishes.keys())——设置(crucial.keys()),设置(dishes.keys())|设置(crucial.keys()),或一组(dishes.keys())^组(crucial.keys())。

#1


11  

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]

#2


2  

If you're using Python 3, the keys method of dictionaries follows the set interface. That means you can do an intersection of the keys of the two dictionaries using the & operator.

如果您使用的是Python 3,那么字典的键方法是遵循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 iterkeys generator), 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 dishes dict, so you don't need to separately look up the value by key.

这里有一个循环的变化,我想我没见过其他人这么做。外部循环从dish dict来获取键和值,因此不需要按键分别查找值。

for key, value in dishes.iteritems(): # use items() in Python 3
    if key in crucial:
        print value

#3


1  

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 (critical)和set(dish))返回两个set的公共键,然后迭代这个集合并返回dish中的值。

[ dishes[x] for x in set (crucial) & set(dishes) ]

#4


0  

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 crucials dictionary. 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 set data structure.

很简单。虽然我注意到你在十字架字典里没有任何值。我不确定这是你的例子的缩写,还是你只关心键。如果您只关心键,那么我假设您使用字典是为了确保惟一性。在这种情况下,应该检查set数据结构。

Example:

例子:

crutial = set(['cheese', 'eggs', 'ham'])

Continuing on we have

继续我们的

if crucial.keys() in dishes.keys():

here you are using the in comparison operator. Example:

这里使用的是in comparison运算符。例子:

5 in [5, 4] #True
3 in [5, 4] #False

If we evaluate crucial.keys() and dishes.keys() we get

如果我们评估cruci. keys()和洗碗机。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 False because 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,因为“鸡蛋”、“培根”、“香肠”(是一个列表)不在列表中(“鸡蛋”、“培根”、“香肠”、“垃圾邮件”)(实际上列表中没有列表,只有字符串)。

Thus you are evaluating as

因此,您正在评估as。

if False:
    print dishes[value] #note value is not defined.

It rather looks like you have mixed/confused the in operator 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 comprehensions which 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迭代器(用于集合中的项)。这类东西有一个语法。它被称为列表综合,你可以在@ShawnZhang和@kmad的答案中找到样本。您可以将它视为筛选和修改(映射)集合的一种简洁的方式,从而返回一个列表。我不想讲得太深入,否则我将在函数式编程的介绍中结束。

Your other option is to use the for .. in iteration and in operators 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 .. .分别在迭代和运算符中。这是@timc给出的解决方案。对于初学者来说,这样的解决方案可能更熟悉或更容易。它清楚地分离了迭代和过滤的行为。它也更像是用其他编程语言编写的,而这些语言并不具有列表理解。那些在Python中工作的人可能更喜欢理解语法。

#5


0  

has_key() has been removed in Python 3: http://docs.python.org/3.1/whatsnew/3.0.html#builtins

在Python 3中已经删除了has_key(): 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列表理解

#6


-1  

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()).

类似地,您可以设定(dishes.keys())——设置(crucial.keys()),设置(dishes.keys())|设置(crucial.keys()),或一组(dishes.keys())^组(crucial.keys())。