Hi there π I'm a New York City based web developer documenting my journey with React, React Native, and Python for all to see. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!
Dictionaries are an essential building block in programming and a fundamental data type in most languages. In Python, we can build a dictionary simply by declaring an empty one.
state_population_dict = {}
We can then add to it by explicitly naming a key-value pair. Here we are adding states to our state_population_dict
dictionary with their respective populations:
state_population_dict["WA"] = 7739000
state_population_dict["NY"] = 19840000
We can then check the value of a key in the dictionary simply by calling the dictionary with the key in brackets.
print(state_population_dict["WA"])
# prints 7739000
If we try to check the value of a key that does not exist on the dictionary, we will get a KeyError
which states the key does not exist on the dictionary.
To check if a key exists on the dictionary before requesting to get its value, we can use the in
keyword.
if ("TX" in state_population_dict):
print(state_population_dict["TX"])
else:
print("TX population not in dictionary")
If you like projects like this and want to stay up to date with more, check out my Twitter @stonestwebdev, I follow back! See you tomorrow for another project.
Top comments (0)