Dictionary in Python

diccionario en python dictionary in python
k

03/11/2023

Dictionaries in Python Language

A dictionary in Python is a collection of pairwise information in the format key:values. The correct syntax is { key : value }

The Python dictionary also stores multiple pieces of information like Lists in Python do, but with the difference that dictionaries do not use numbers in their indexes, instead the indexes are keys.

At the same time, dictionary keys are set manually, unlike the indexes in Lists which are assigned automatically by Python.

Keys in a dictionary can NOT be duplicated, i.e. they must be UNIQUE.

Py

car = {'make':'Renault','colour':'red','engine':1.6}

The keys in the example above would be – make, colour, engine – so there could not be – make or colour – more than once. That is why they are said to be unique.

Creating a dictionary in Python

There are several ways to create a dictionary in Python. On the one hand we have the dict ( ) constructor option and on the other hand, the use of the  { }.

 

Py

# create a dictionary with the dict ( ) constructor
fruit = dict( )
# We want to see on the console the type of data fruit is
print(type(fruit))
# dictionary type
<class 'dict'>

As we see above we have created a dictionary called – fruit – and we have assigned the constructor – dict ( ) to it. This way it will create an empty dictionary with no elements.

When using print(type(fruit)) we want to display the type of – fruit – on the screen and we get < class ‘dict’> as a result indicating that it is a dictionary.

Py

# create the dictionary with {} 
fruit = { }
# Show on the console the type of data fruit is
print(type(fruit))
# dictionary type
<class 'dict'>

In this second method we use the { } instead of dict( ). And everything else is exactly the same as in the previous case.

We create an empty dictionary with no elements called – fruit.

By using print(type(fruit)) we want the type of – fruit – to be displayed on the screen and we get < class ‘dict’> confirming that it is a dictionary.

Accessing a dictionary in Python

To understand how we access the elements of a dictionary in Python, the syntax is dict[key].

Py

Py

# Let´s say we have a new dictionary called numbers
numbers = { 'uno':'one', 'dos':'two', 'tres':'three' }
# if we want to access to value three
numbers['tres']
# On the console will show
three

In the above example for the key – one – we have the value – one, etc. So for key tres we have the value three.

If by mistake we pass a key that is not part of the dictionary, Python will return an error message – KeyError ‘wrong key entered‘.

Adding items to a dictionary in Python

Tenemos varias formas de añadir elementos a un diccionario en Python. La primera opción es con la sintaxis siguiente: diccionario[key] = value.

Py

# numbers dictionary has new data as new example
numbers = { 10:'diez', 20:'veinte', 30:'treinta', 40:'cuarenta' }
# if we want to add another element
numberos[50] = 'cincuenta'
# On console we will see
numbers = { 10:'diez', 20:'veinte', 30:'treinta', 40:'cuarenta', 50:'cincuenta }

The other method for adding items to a dictionary is with the update ( ) method.

The syntax of the update method is dictionary.update({key:value}) . It is important to mention that the argument we pass inside the parenthesis of update must be between { }.

Py

# dictionary called car
car = { 'make':'Fiat','colour':'Green','doors':'three' }
# We add a new element to car with update()
car.update({'engine':'petrol'}
# After the update
car = { 'make':'Fiat','colour':'Green','doors':'three','engine':'petrol' }

If you need to add more than one element with the update ( ) method, you can do so by assigning them a variable and then inserting the variable inside the update brackets.

Py

# car dictionary
car = { 'make':'Fiat','colour':'Green','doors':'three' }
# Add a new element to car with update()
# Assign the new key:values to a variable called new_car
new_car = {'engine':'petrol','year':2010}
# Update info
car.update(new_car)
# car will be updated like this
car = { 'engine':'Fiat','colour':'Green','doors':'three','engine':'petrol','year':2010 }

 

Deleting items from a dictionary in Python

We will see two options for deleting elements in a dictionary: pop ( ) and del ( )

With the pop( ) method we remove the element from the dictionary and return the element we have removed on the screen. When using pop() we must pass as argument the key of the element we want to remove.

Py

# Using the car dictionary example we will remove the value of key -> colour
car = { 'engine':'Fiat','colour':'Green','doors':'three','engine':'petrol','year':2010 }
element_removed = car.pop('colour')
# on the console
print(element_removed)
Green

 

On the other hand, with the del ( ) method, when we delete the element it is not returned on screen, as in the case of pop ( ).

With del ( ) we also use the key of the element we want to remove from the dictionary.

The syntax of del () is del dictionary[key]

Py

# Using the car dictionary example we will remove the value of key -> year
car = { 'engine':'Fiat','doors':'three','engine':'petrol','year':2010 }
# Remove the value of key -> year
del car['year']
# on the console
print(car)
{ 'engine':'Fiat','doors':'three','engine':'petrol' }

 

Read items from a dictionary in Python

There are several ways to read items from a dictionary.

dict.items( ) -> this method returns both the keys and the values of the dictionary.

dict.keys( ) -> returns only the dictionary keys.

dict.values( ) -> returns only the values of the dictionary.

 

Py

# We are going to work with a new dictionary called cadena
cadena = {1:'one',2:'two',3:'three',4:'four',5:'five'}
# If we want to get the data from cadena with dict.items( )
for key,value in cadena.items( ):
print(key,':',value)
# on console will show keys and values
1:one
2:two
3:three
4:four
5:five
# If we want to get the data from cadena with dict.keys( )
for i in cadena.keys( ):
print(i)
# on console will show just the keys
1
2
3
4
5
#  If we want to get the data from cadena with  dict.values( )
for i in cadena.values( ):
print(i)
# on console will show just the values
one
two
three
four
five

In short, the Python dictionary allows us a wide variety of options when it comes to handling data. This is a lesson for Python ´s students as they ask about it when they start programming in this language.

If you want to continue learning how to program in Python, you can find more resources in this link. Musa Arda

Creatuwebpymes, is a web design and programming company in the Canary Islands that ❤️ programming.

creatuwebpymes quien somos

Francisco Brito Diaz

CEO of Creatuwebpymes, is a web design company and marketing digital based in Lanzarote – Canary Islands