How does "&" work in comparing two type of data in this code?
Question:
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}
Answers:
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}
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}
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}