What is Dictionary?

We have said that there are mutable (modifiable) data types that contain different data types such as Tuple and List data types in dictionaries and are shown with curly braces.

Dictionaries are a little different because Dictionaries consist of two parts; keys and values, value part can contain all data type but keys part can only be of string and int type.

How to Use Dictionaries?

Before I show its usage, Lets explain why dictionary; Imagine that you are making an English dictionary, how would it be without a database. You have to write an if condition for each word. Each word is a conditional cycle, which makes the program tiring. Let me show you with an example;

"""Romanian Dictionary Application"""
word = input("Enter the english word: ")

if word == "Computer":
    print("Calculator")
elif word == "School":
    print("Şcoală")
elif word == "Memory":
    print("Memorie")
elif word == "House":
    print("Casa")
elif word == "Bus":
    print("Autobuz")
elif word == "Car":
    print("Mașină")

You will probably have written code like this.

Let’s write the same application with Dictionaries.

"""Romanian Dictionary Application"""
word = input("Enter the english word: ")
 
dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}

In this way, you will have written more neat and readable code, and since Dictionaries are mutable (modifiable) data types, they can be easily added, deleted, changed, etc. we can do the work.

Accessing Dictionary Items

Dictionaries are based on key=value relationships, and every value has a key value. Then we can reach the value with the key we know. Let’s give an example right away;

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}

print(dictionary["Computer"])

# Calculator

Dictionary Methods

Let’s list the dictionary methods immediately;

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
 '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
 '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
 '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
 '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys',
 'pop', 'popitem', 'setdefault', 'update', 'values']

If we omit __X__ private methods

['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

We will cover their methods.

keys Method

At the beginning of this blog post, while defining Dictionaries, we said that Dictionaries consist of key and value. Here, this method gives all the keywords in the dictionary, let me show you with an example;

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}

print(dictionary.keys())

dict_keys(['Computer', 'School', 'Memory', 'House', 'Bus', 'Car'])

values Method

This method also returns all values in a dictionary.

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}
 
print(dictionary.values())
 
dict_values(['Calculator', 'Şcoală', 'Memorie', 'Casa', 'Autobuz', 'Mașină'])

items Method

This method returns both keys and values.

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}
 
print(dictionary.items())
 
dict_items([('Computer', 'Calculator'), ('School', 'Şcoală'), ('Memory', 'Memorie'), ('House', 'Casa'), ('Bus', 'Autobuz'), ('Car', 'Mașină')])

get Method

Before explaining this method, let’s make an application;

word = input("Enter a word: ")
dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}
 
if word in dictionary:
    print(dictionary[word])
else:
    print("The word you are looking for is not found in the dictionary.")
 
# Enter a word: Computer
# Calculator
 
# Enter a word: whoami
# The word you are looking for is not found in the dictionary.

Here, the word we are looking for gives a word if it exists, if not, we wrote a program that gives us a text.

Here’s the get method that allows us to do the same function without writing the if condition loop.

word = input("Enter a word: ")
dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}

print(dictionary.get(word, "The word you are looking for is not found in the dictionary."))
 
# Enter a word: Bus
# Autobuz

# Enter a word: Driver
# The word you are looking for is not found in the dictionary.

copy Method

This method allows us to copy a Dictionary.

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}
 
dictionary2 = dictionary.copy()
print(dictionary2)

# {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie","House":"Casa","Bus":"Autobuz","Car":"Mașină"}

clear Method

As the name suggests, this method performs the cleaning function, but there is one thing you need to be careful about, this deletes the inside of the dictionary.

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}
 
dictionary.clear()
print(dictionary)

# {}

Well, if you are asking how to delete the dictionary completely, let me show you right away;

del dictionary

We can also delete an item in the dictionary this way;

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}
 
del dictionary["Computer"]

In this way, we have deleted the “Computer” item.

pop Method

This method is deleting a single item with a keyword. It also prints the key value of the deleted item to the screen.

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}
 
dictionary.pop("School")

In this way, we have deleted the “School” item.

popitem Method

This method does the same as the pop method, but this method takes no parameters and deletes a random item.

dictionary = {"Computer":"Calculator","School":"Şcoală","Memory":"Memorie",
"House":"Casa","Bus":"Autobuz","Car":"Mașină"}

dictionary.popitem()

setdefault Method

This method is the same as the get method. If there is no key, you can print it by giving a value to that key.

If the searched word is found;

numbers = {"1":"one","2":"two","3":"three","4":"four","5":"five"}

print(numbers.setdefault("4"),)

# four

If the searched key does not exist;

print(numbers.setdefault("8","eight"),)
 
# eight

update Method

This method is used to update the Dictionary. Let me show you its usage with an example;

Let’s say we have a list of students and these students have grades;

list_1 = {"Baransel":70,"Alex":50,"Josh":60,"Batu":75}

We want to add 10 points to the grades, so the new version will be as follows;

list_2 = {"Baransel":80,"Alex":60,"Josh":70,"Batu":85}

If we want it to be like the second list, the action we will do is;

list_1.update(list_2)
print(list_1)
 
# {"Baransel":80,"Alex":60,"Josh":70,"Batu":85}