Python Dictionary Tutorial

Python Dictionary data type is used to implement real-world dictionary logic. Python dictionary is used to store single or multiple items where these items consist of key/value pairs. A dictionary is created with curly brackets and putting key-value pairs by paring them : . Key-value pairs are separated with a comma.

Create Dictionary

A Python dictionary can be created just using curly brackets and putting key-value pairs inside it. In the following example we create a dictionary with 3 items or key-value pairs.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

While creating or defining a dictionary the definition can span multiple lines without problem. But the key-value pairs are atomic and a single key-value pair do not span multiple lines.

names = { "1":"ismail" , 
          "2":"ali" , 

In this dictionary "1" is the key and "ismail" is the value and they are paired together with the : to create an item. Every item is separated with the , comma.

Alternatively an empty dictionary can be created without providing any item or key-value pair. We can use the dict() method which will create a dictionary without any item and set to the variable. In the following example, we have created a dictionary named names that do not have any data or items.

names = dict()

Access Dictionary Item

You can access items in a dictionary in different ways by providing the key. The most popular method is used the square brackets and putting the key inside them. If the related key exist its value will be returned. If the provided key do not exist nothing will be returned.

a = names["1"]
# Output is ismail

c = names["3"]
# Output is elif

There is an alternative way to [] accessor which is the get() mehtod. The get() method is provided by the dictionary itsself can be called providing the key.

a = names.get("1")
# Output is ismail

c = names.get("3")
# Output iselif

Change Item Value

Item values can be easily changed by using their keys. In order to change an item value its key should be specified with the [] square brackets and the new value should set like an variable assignment.

names["1"] = "ahmet"

Display Dictionary Length

Dictionaries may contains single or more items. The legth or item count of a dictionary can be listed by using the len() method easily.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

#Output is 3

Check If Key Exist

The in keyword is used to check if the given key exists in the specified dictionary. In the following example, we will check if the "1" exist in the dictionary.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

if "1" in names:

#Output Exist

Check If Value Exist

Even there is not native way like checking key existence we can also check if the specified dictionary has given value. First we will extract all values of the dictionary into list and then use the in keyword.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

if "ismail" in names.values():

#Output Exist

Add New Item

Adding new item into a dictionary is very easy. It is the same as changing a value in a dictionary. We will just provide the key in square brackets and assign the value we want to set.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

names["4"] = "ahmet"

Remove/Delete Item

The dictionary provides method named pop() in order to return and remove/delete the item specified with its key. We will provide the item key which will be removed.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }


Alternatively the popitem() method can be used to remove/delete the last added or inserted item. As we expect there is no need to specify any key.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }


Also the del() method can be used to remove or delete specified item from the dictionary. The item key should be specified. If the key is not specified the dictionary will be deleted completely with all its items.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }


Display All Keys

The keys() method can be used to return or display all keys of the specified dictionary. The keys will provided as a list.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

keys = names.keys()

Display All Values

The values() method can be used to return or display all values of the specified dictionary. The values will be provided as a list.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

keys = names.values()

Copy or Clone Dictionary

A dictionary can be copied or cloned by using the copy() method which will return the complete copy of the dictionary.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

newnames = names.copy()

An alternative way to copy or clone a dictionary is using the dict() method where we will provide the dictionary we want to copy as parameter.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

newnames = dict(names)

Nested Dictionary

Up to now we have working with single level dictionaries where items are not nested. Nested dictionary contains single or more items where the item value is a dictionary too.

users = { "─░smail Baydan":{"username":"ismail","password":"123"}
          "Ahmet Baydan":{"username":"ahmet","password":"456"}}

Loop or Iterate Items

Dictionary data type is an iterable type which means the items of a dictionary can be iterated or looped using mechanisms like for keyword. In every step of the iteration, the next item will be returned with its key and we can use this key to get value.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

for key in names:
   print("Key is "+key)
   print("Name is "+names[key])

We can also iterate over the values without using the key. We will use the dictionary values() method which will return all values of the specified dictionary in a iterable way.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

for name in names.values():
   print("Name is "+name)

We can also iterate over the dictionary items by returning both key and value. The dictionary items() method can be used to return both key and values in an iterable way where we can loop with for.

names = { "1":"ismail" , "2":"ali" , "3":"elif" }

for key , value in names.items()
   print("Key is "+key)
   print("Name is "+value)

Merge or Join Dictionaries

Multiple dictionaries can be merged together in different ways. The first way is using the update() method where the first dictionary content will be provided to the second one update() method and all items in the second dictionary will be updated and if the first dictionary items do not exist they will be added.

names1 = { "1":"ismail" , "2":"ali" , "3":"elif" }

names2 = { "4":"ecrin" , "5":"ahmet" }


Alternatively we can make things more clear and create an empty dictionary where first and second dictionaries are merged into thid thrid empty dictionary.

names1 = { "1":"ismail" , "2":"ali" , "3":"elif" }

names2 = { "4":"ecrin" , "5":"ahmet" }

names = dict()



Dictionary Methods

As a popular data type in the Python dictionary provides useful methods to operate. The following methods are provided by dictionaries.

clear()Removes all the items or key-value pairs from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value. This can be called as sub-dictionary
get(key)Returns the value of the specified key
items()Returns a list containing a tuple for each key-value pair
keys()Returns a list fo all the dictionary’s keys
pop(key)Removes the item with the specified key
popitem()Removes the last inserted item or key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: add the item with the provided key-value
update()Updates the dictionary with the specified key-value pairs
values()Returns a list of all the values in the dictionary

Leave a Comment