Compare two dictionary keywords and return a value

I am starting Python, but I have tried this syntax and I cannot figure out what was really obscure.

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 there is a key in the dishes (in this case eggs ), it will return 2 . It seems simple enough, but I believe I should mess up some syntax somewhere. If someone could correct me a little, it would be very useful.

The actual dictionaries I'm comparing with are about 150 keys, but I hope this code is quite simple.

+7
source share
6 answers

You need to sort out the keys in critical situations and compare them with the keys of the dishes. So there is a directly modified version of your code.

 for key in crucial.keys(): if key in dishes.keys(): print dishes[key] 

It might be better to specify (no need to specify .keys):

 for key in crucial: if key in dishes: print dishes[key] 
+10
source

If you are using Python 3, the keys dictionary method follows the set interface. This means that you can intersect the keys of two dictionaries with the & operator.

 for key in crucial.keys() & dishes.keys(): print(dishes[key]) 

Or if you need a list of values:

 result = [dishes[key] for key in crucial.keys() & dishes.keys()] 

In Python 2, you could manage the same thing by explicitly creating sets (possibly from the iterkeys generator), but it would probably be better to just loop over the keys, as several other answers suggest.

Here's a variation of the loop that I don't think I saw anyone else. The outer loop gets both keys and values ​​from dishes dict, so you don’t need to separately search for the value by key.

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

using list comprehension well

 [ dishes[x] for x in crucial if dishes.has_key(x) ] 

or according to gnibbler:

 [ dishes[x] for x in crucial if x in dishes ] 

this expression will iterate critical each key in the decisive one, if the key is in dishes, it will return the value of the same key in dishes, finally it will return a list of all matching values.

or, you can use this method (set (critical) and set (dishes)) to return the common keys of both sets, then iterate over this set and return the values ​​to the dishes.

 [ dishes[x] for x in set (crucial) & set(dishes) ] 
+1
source

has_key() was removed in 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

0
source

If you are not already familiar with Python REPL (Read-Evaluate-Print-Loop is where you enter the code, press Enter and it will appreciate right away), this would be a good tool here.

So, let's start breaking your code.

 crucial = {'eggs': '','ham': '','cheese': ''} dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} 

Simple enough. Although I note that you have no meanings in the crucials dictionary. I'm not sure if this is an abbreviation for an example or if you just care about the keys. If you only care about keys, then I assume that you use a dictionary to ensure uniqueness. In this case, you should check the set structure.

Example:

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

Continuing, we have

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

here you use the comparison operator in . Example:

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

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

  >>> crucial.keys() ['cheese', 'eggs', 'ham'] >>> dishes.keys() ['eggs', 'bacon', 'sausage', 'spam'] 

therefore, at runtime, your code evaluates to

  ['cheese', 'eggs', 'ham'] in ['eggs', 'bacon', 'sausage', 'spam'] 

which returns False because the value of ['eggs', 'bacon', 'sausage'] (which is the list) is not in the list ['eggs', 'bacon', 'sausage', 'spam'] (actually in there are no lists in this list, only lines).

So you rate how

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

Most likely, you mixed / confused the in operator, which returns a boolean and an iterator ( for item in collection ). There is a syntax for these kinds of things. It's called a list of concepts , which you can find in the answers of @ShawnZhang and @kmad. You can think of it as a complicated way to filter and modify (display) a collection, returning a list as a result. I do not want to delve into it, or I will talk about functional programming.

Another option is to use the for .. in operators of iteration and in separately. This solution by @timc gave. Such solutions are probably more familiar or easier for beginners. It clearly separates the iteration and filtering behavior. It also looks more like what would be written in other programming languages ​​that have no equivalent for list comprehension. Those who work a lot in Python are likely to prefer the understanding syntax.

0
source
 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()) set(dishes.keys()) | set(crucial.keys()) or set(dishes.keys()) ^ set(crucial.keys()) .

-one
source

All Articles