Dictionaries in Python

Halil Yıldırım
Jun 22 · 2 min read
Photo by Syd Wachs on Unsplash

In Python, Dictionaries may come in handy on your projects. And this is my very first publication. And I’m going to do my best to give you a good understanding of how you can use dictionaries. Let’s get started.

Let’s first create a dictionary.

employee = {'name': 'Halil', 'salary':10000, 'languages':['English', 'Turkish']}

name, salary and languages are called keys.
Halil, 10000, [‘English’, ‘Turkish’] are called values.

In order to access to value of a key in your dictionary, you can simply do it like below;

print(employee['name'])

This code above will print out the name of employee: Halil
Another way of doing this to use get method.

print(employee.get('name'))

It will print out again Halil.

Another advantage of this function is that when you are calling a key that is not in your dictionary. You can print out an error with a specified message. Like I did below, as surname is not in the employee dictionary when you call surname, it will give an error: “There is no key like that” You can write your own custom error message.

print(employee.get('surname', 'There is no key like that'))

When you want to access to values in your dictionary. It is as simple as like below:

print(employee.values())

When you want to access to the items in your dictionary, you can simply write employee.items().

employee.items()

What you can do with them;

for key, value in employee.items():
print(key, value)

The output will be after executing the code above;

name Halil
salary 10000
languages [‘English’, ‘Turkish’]

Bolded are keys and others are values.

I hope you will find it useful. Thank you very much for reading.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade