DEV Community

James Hubert
James Hubert

Posted on

1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Need to crop and overlay a logo on 999.999 web images?

No problem! Combine hundreds of advanced image effects directly through an API. Discover all you can do with Cloudinary Image and Video APIs.

Discover

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay