Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does "&" work in comparing two type of data in this code?

I am reading Python Cookbook: "1.17. Extracting a Subset of a Dictionary". I got confused with the "&" usage in one piece of the below code example. Who may help elaborate on it a bit?

How does prices.keys() & tech_names work here?

prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 205.55,
    'HPQ': 37.20,
    'FB': 10.75
}
tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
p2 = {key: prices[key] for key in prices.keys() & tech_names}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The & operator is used to create the intersection of the sets of keys in prices and the values in tech_names.

See the section on Dictionary view objects:

Keys views are set-like since their entries are unique and hashable. […] For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

Also see the intersection methods section for set:

 set & other & ...

Return a new set with elements common to the set and all others.

So, the code only defines the prices for the symbols listed in the tech_names set.

Another way of spelling this would be to use a if filter in the dictionary comprehension; this has the advantage that you can then use prices.items() and access the symbol and the price at the same time:

p2 = {symbol: price for symbol, price in prices.values() if symbol in tech_names}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading