Why weren’t my dictionary values printed?


Why weren’t my dictionary values printed?


There are several reasons, but some common issues are:

  1. Using parentheses instead of brackets to access a dictionary key value, like this: residents("Sloth")
  2. Not matching the capitalization and/or spelling of the key found in the dictionary, like this:
  3. Trying to write both at once, like this: residents["Sloth", "Burmese Python"]
1 Like

Why trying to write both at once , the two values can’t be printed at the same time?


Not the way shown above. They could like this:

#Python 3
print(residents["Sloth"], residents["Burmese Python"])

#Python 2
print residents["Sloth"], residents["Burmese Python"]

When I tried the following code:

print residents["Sloth" and "Burmese Python"]

it printed the correct value for Burmese Python, but didn’t print Sloth. Why?

Unfortuantely you can’t use dictionary names like this. Notably and in Python is a reserved keyword for the logical and.

In the case of strings it evaluates the boolean of these strings, e.g. bool( “Sloth”) and bool(“Burmese Python”] which are both true as they are not empty strings leading to the right hand value being returned. This effectively leads to print residents[“Burmese Python”] as the statement. You’d have to look up how logical statements work on strings if you want the full background.

If you wanted multiple names youd have to use looping/comprehension to cycle through the keys you wanted or use something like map or itemgetter to address them.

For two values, maybe just address them directly. I was curious if there we as proper way to do this for multiple values and there are a number of different options (more than listed below). Included a few just in case anyone was curious (they may not be the best options)-

value0a, value0b = residents["Sloth"], residents["Burmese Python"]

key_names = ["Sloth", "Burmese Python"]
value1a, value1b = [residents[key] for key in key_names]
value2a, value2b = [residents.get(key) for key in key_names]
value3a, value3b = list(map(residents.get, key_names))
value4a, value4b = itemgetter(*key_names)(residents)

Note these are solutions for Python3, I’ve not tried them on 2 (map for example is different).