Reputation: 57
First of all, thank you for your help in advance. I am novice to coding and currently studying Python using the book, 'Automate the Boring Stuff with Python' and I have a conceptual question on multiple assignment. https://automatetheboringstuff.com/chapter5/
Here are the excerpts from the book:
>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False
So I tried,
>>> 7 in spam
expecting True
, but got False
.
Then I tried,
>>> 7 in spam.values()
which returned True
.
So, it seems string values work the same way, but integers behave differently.
Why is this the case?
Upvotes: 2
Views: 119
Reputation: 8583
In
checks against the keys only, whereas the values are accessible via dict.values()
, dict.values()
gives access to the values of a dictionary. Both .keys()
and .values()
return an iterable.
For a more elegant/shorter way to check for an existing key you could use dict.get(key)
. This returns the value of the given key if the key is in the dictionary, and a 'fall-back' return value if not. This 'fall-back' return value is None
by default (if not specified) or can be set by the programmer by using dict.get(key, return_if_not_in_dict)
. For a more detailed explanation see this question or the following code:
In [10]: spam = {'name': 'Zophie', 'age': 7}
In [11]: 'name' in spam
Out[11]: True
In [12]: 'Zophie' in spam
Out[12]: False
In [13]: 'name' in spam.keys()
Out[13]: True
In [14]: 'Zophie' in spam.values()
Out[14]: True
In [15]: type(spam.keys())
Out[15]: dict_keys
In [17]: type(spam.values())
Out[17]: dict_values
In [18]: spam.get('name')
Out[18]: 'Zophie'
In [19]: spam.get('some invalid key') # returns `None`, so no output here
In [20]: spam.get('some invalid key', 'not in here')
Out[20]: 'not in here'
In [21]: bool(spam.get('name'))
Out[21]: True
In [22]: bool(spam.get('some invalid key'))
Out[22]: False
Upvotes: 0
Reputation: 363
Your problem is that 7 is a value, not a key. spam = {'name': 'Zophie', 'age':7}
So if you do:
7 in spam >> False
'age' in spam >> True
7 in spam.values() >> True
7 in spam.keys() >> False
foo = {key0 : value0 , key1 : value1 ... keyN: valueN}
Take in to account, that in python the in
looks for dictionary's keys list, not the values list. Unless you specify to do so.
Upvotes: 2