DEV Community

James Hubert
James Hubert

Posted on

Intro to Python: Day 19 - Building a Dictionary

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 = {}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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)