How to search through dictionaries?
Simple enough
if entry in people:
print ("Name: " + entry)
print ("Age: " + str(people[entry]) + "\n")
Python also support enumerate to loop over the dict.
for index, key in enumerate(people):
print index, key, people[key]
If you want to know if key
is a key in people
, you can simply use the expression key in people
, as in:
if key in people:
And to test if it is not a key in people
:
if key not in people:
You can reference the values directly. For example:
>>> people = {
... "Austun": 25,
... "Martin": 30}
>>> people["Austun"]
Or you can use people.get(<Some Person>, <value if not found>)
.