Skip to content

Python Dictionary, with Examples

Learn how Python dictionaries work: declaring them, looping over key-value pairs and using methods like get, pop, update and more, with practical examples.

You can download the project for this post by clicking HERE.

Dictionaries in Python are a type of data structure that lets you store an unordered set of key-value pairs, where the keys are unique within a dictionary (that is, two elements cannot have the same key). Dictionaries are data structures that are very common in other programming languages, although some languages, like Java, call them by different names such as "Map" (see the post "Map in Java, with examples").

Let’s look at an example of how we would declare a dictionary in Python whose elements are the players of the Spanish national team, where the key is the shirt number (a unique key) and the value is the player’s name.

# Defino la varible 'futbolistas' como un diccionario. No es necesario declarar que tipo de dato es
futbolistas = dict()

futbolistas = {
    1 : "Casillas", 15 : "Ramos",
    3 : "Pique", 5 : "Puyol",
    11 : "Capdevila", 14 : "Xabi Alonso",
    16 : "Busquets", 8 : "Xavi Hernandez",
    18 : "Pedrito", 6 : "Iniesta",
    7 : "Villa"
}

As we can see, the dictionary is declared between the ‘{}’ characters and we separate each of the elements with commas (‘,’). We define each element with its key:value pair, and both the key and the value can be of any data type (‘int’, ‘float’, ‘chr’, ‘str’, ‘bool’, ‘object’).

Next, let’s loop over the dictionary (with a foreach) and print its key:value pairs (later we will see all the dictionary methods):

# Recorrer un diccionario, imprimiendo su clave-valor
for k,v in futbolistas.items():
    print "%s -> %s" %(k,v)

The result of this code is the following:


1 -> Casillas
3 -> Pique
5 -> Puyol
6 -> Iniesta
7 -> Villa
8 -> Xavi Hernandez
11 -> Capdevila
14 -> Xabi Alonso
15 -> Ramos
16 -> Busquets
18 -> Pedrito

Now let’s go over the methods (or functions) for working with dictionaries in Python, and then we’ll look at examples of how these methods work:

# Declaración de un diccionario
diccionario = dict()

# Devuelve el numero de elementos que tiene el diccionario
len(dict)

# Compara el número de elementos distintos que tienen los dos 
cmp (dict1,dict2)

# Devuelve una lista con las claves del diccionario
dict.keys()

# Devuelve una lista con los valores del diccionario
dict.values()

# Devuelve el valor del elemento con clave key. Sino devuelve default
dict.get(key, default=None)

# Inserta un elemento en el diccionario clave:valor. Si la clave existe no lo inserta
dict.setdefault(key, default=None)

# Insertamos un elemento en el diccionario con su clave:valor
dict['key'] = 'value'

# Eliminamos el elemento del diccionario con clave key
dict.pop('key',None)

# Devuleve la copia de un diccionario dict2 = dict.copy()
dict.copy()

# Elimina todos los elementos de un diccionario
dict.clear()

# Crea un nuevo diccionario poniendo como claves las que hay en la lista y los valores por defecto si se les pasa
dict.fromkeys(list, defaultValue)

# Devuelve true si existe la clave. Sino devuelve false
dict.has_key(key)

# devuelve un lista de tuplas formadas por los pares clave:valor
dict.items()

# Añade los elementos de un diccionario a otro
dict.update(dict2)

Now that we’ve seen the methods (or functions) that let us work with dictionaries, let’s show how to use them. For that we’ll use the ‘futbolistas’ dictionary that we declared at the beginning, in which we stored football player elements that have their shirt number as the key (that is, an ‘int’) and their name as the value (a ‘string’).

First, let’s show how to count the elements of a dictionary, which we do like this:

# Vemos cuantos elementos tiene nuestro diccionario
numElem = len(futbolistas)
print "\nNumero de elementos del diccionario len(futbolistas) = %i" %numElem

The output of that code snippet is:


Numero de elementos del diccionario len(futbolistas) = 11

With the "keys()" method we get a list with the dictionary’s keys, and in the same way, with the "values()" method we get a list with the dictionary’s values. In the following code snippet we see how to get these lists:

# Imprimimos una lista con las claves del diccionario
keys = futbolistas.keys();
print "\nClaves del diccionario futbolistas.keys(): \n%s" %keys

# Imprimimos en una lista los valores del diccionario
values = futbolistas.values()
print "\nValores del diccionario futbolistas.values(): \n%s" %values

The output of this code snippet is the following:


Claves del diccionario futbolistas.keys(): 
[1, 3, 5, 6, 7, 8, 11, 14, 15, 16, 18]

Valores del diccionario futbolistas.values(): 
['Casillas', 'Pique', 'Puyol', 'Iniesta', 'Villa', 'Xavi Hernandez', 'Capdevila', 'Xabi Alonso', 'Ramos', 'Busquets', 'Pedrito']

With the "get(key)" method, passing a key as a parameter, we get the value of the element that has that key:

# Obtenemos el valor de un elemento dada su clave
elem = futbolistas.get(6)
print "\nObtenemos el valor cuya clave es '6' futbolistas.get(6): %s" %elem

As a result, we get the name of the player with key = 6:


Obtenemos el valor cuya clave es '6' futbolistas.get(6): Iniesta

Next we’ll look at two ways of inserting elements into the dictionary. The first is the simplest (as if it were an associative array): you pass the key between square brackets and assign it a value:

# Añadimos un nuevo elemento a la lista
futbolistas[22] = 'Navas'
print "\nDiccionario tras añadir un elemento: futbolistas[22] = 'Navas' \n%s" %futbolistas

As a result, the dictionary has one more element:


Diccionario tras añadir un elemento: futbolistas[22] = 'Navas' 
{1: 'Casillas', 3: 'Pique', 5: 'Puyol', 6: 'Iniesta', 7: 'Villa', 8: 'Xavi Hernandez', 10: 'Cesc', 11: 'Capdevila', 14: 'Xabi Alonso', 15: 'Ramos', 16: 'Busquets', 18: 'Pedrito', 22: 'Navas'}

The second way to insert an element is with the "setdefault(key,default=value)" method, which takes a key and a value as parameters. This method has the peculiarity that it only inserts the element into the dictionary if no element with that key exists. If an element with that key exists, it does not perform the insertion:

# Insertamos un elemento en el array. Si la clave ya existe no inserta el elemento
elem2 = futbolistas.setdefault(10,'Cesc')
print "\nInsertamos un elemento en el diccionario. Si la clave existe no lo inserta" \
      "\nfutbolistas.setdefault(10,'Cesc'): %s" %elem2

The result of the previous code snippet is the following:


Insertamos un elemento en el diccionario. Si la clave existe no lo inserta
futbolistas.setdefault(10,'Cesc'): Cesc

The next method we’ll look at, "pop(key)", removes from the dictionary the element whose key is the one we pass as a parameter. For example, let’s delete the element with key = 22:

# Eliminamos un elemento del diccionario dada su clave
futbolistas.pop(22)
print "\nDiccionario tras eliminar un elemento: futbolistas.pop(22) \n%s" %futbolistas

In the result of this code snippet, we can see that the element with key = 22 was indeed deleted:


Diccionario tras eliminar un elemento: futbolistas.pop(22) 
{1: 'Casillas', 3: 'Pique', 5: 'Puyol', 6: 'Iniesta', 7: 'Villa', 8: 'Xavi Hernandez', 10: 'Cesc', 11: 'Capdevila', 14: 'Xabi Alonso', 15: 'Ramos', 16: 'Busquets', 18: 'Pedrito'}

To make a copy of a dictionary, you use the "copy()" method:

# Hacemos una copia del diccionario
futbolistasCopy = futbolistas.copy();
print "\nRealizamos una copia del diccionario futbolistasCopy=futbolistas.copy(): \n%s" %futbolistas

As we can see, the result is a new dictionary called ‘futbolistasCopy’ that contains the same elements as the ‘futbolistas’ dictionary:


Realizamos una copia del diccionario futbolistasCopy=futbolistas.copy(): 
{1: 'Casillas', 3: 'Pique', 5: 'Puyol', 6: 'Iniesta', 7: 'Villa', 8: 'Xavi Hernandez', 10: 'Cesc', 11: 'Capdevila', 14: 'Xabi Alonso', 15: 'Ramos', 16: 'Busquets', 18: 'Pedrito'}

To remove the contents (or elements) of a dictionary, we use the "clear()" method:

# Eliminamos los elementos de un diccionario
futbolistasCopy.clear()
print "\nEliminamos los elementos de un diccionario futbolistasCopy.clear(): %s" %futbolistasCopy

We can see that the previous code snippet removes the contents of the dictionary, but doesn’t delete the dictionary itself:


Eliminamos los elementos de un diccionario futbolistasCopy.clear(): {}

With the "fromkeys(listKey,default=value)" method, we create a dictionary whose keys are the ones we pass as a parameter in a list. If we pass a second parameter, it will be used as the value of each of the elements. Let’s look at an example:

# Creamos un diccionario a partir de una lista con las claves
keys = ['nombre', 'apellidos', 'edad']
dictList = dict.fromkeys(keys, 'nada')
print "\nCreamos un diccionario a partir de una lista dictList = dict.fromkeys(keys, 'nada'): \n%s" %dictList

As a result, it creates a dictionary called ‘dictList’, with the keys we passed in the list and with the value ‘nada’ that we passed as a parameter:


Creamos un diccionario a partir de una lista dictList = dict.fromkeys(keys, 'nada'): 
{'apellidos': 'nada', 'nombre': 'nada', 'edad': 'nada'}

The method that lets us check whether a key exists is the "has_key(key)" method. Let’s look at an example:

# Comprobamos si existe o no una clave
exit2 = futbolistas.has_key(2)
exit8 = futbolistas.has_key(8)
print "\nComprobamos si existen los elementos 2 y 8 \n\tfutbolistas.has_key(2) = %s " \
      "\n\tfutbolistas.has_key(8) = %s" %(exit2,exit8)

The result of the previous key check is the following:


Comprobamos si existen los elementos 2 y 8 
	futbolistas.has_key(2) = False 
	futbolistas.has_key(8) = True

Another very useful method, especially for doing a foreach over the dictionary and getting its key:value pairs, is the "items()" method, which returns the dictionary’s elements as tuples, where in each one the key is in the first position and the value in the second. Let’s look at an example:

# Devolvemos los elementos del diccionario en tuplas
tuplas = futbolistas.items()
print "\nPasamos el diccionario a tuplas con clave-valor: tuplas = futbolistas.items() \n%s" %tuplas

As a result, we see that it does indeed return a list of tuples with the key:value pairs:


Pasamos el diccionario a tuplas con clave-valor: tuplas = futbolistas.items() 
[(1, 'Casillas'), (3, 'Pique'), (5, 'Puyol'), (6, 'Iniesta'), (7, 'Villa'), (8, 'Xavi Hernandez'), (10, 'Cesc'), (11, 'Capdevila'), (14, 'Xabi Alonso'), (15, 'Ramos'), (16, 'Busquets'), (18, 'Pedrito')]

Finally, let’s look at the "update(dict)" method, which lets us merge the elements of two dictionaries. This method inserts into the dictionary the elements of the dictionary passed as a parameter whose keys are not already in the dictionary. Let’s look at the following example:

# Mergeamos dos diccionarios
suplentes = {
    4:'Marchena', 9:'Torres', 12:'Valdes',
    13:'Mata' , 17:'Arbeloa', 19:'Llorente',
    20:'Javi Martinez', 21:'Silva', 23:'Reina'
}

futbolistas.update(suplentes)
print "\nAñadimos los elementos de un diccionario a otro futbolistas.update(suplentes): \n%s" %futbolistas

As we can see in this example, we created a new dictionary with the ‘suplentes’ (substitute) players and merged it into the ‘futbolistas’ dictionary. This way the ‘futbolistas’ dictionary now has all the players (starters + substitutes) of the Spanish national team that won the world championship in 2010. The result is the following:


Añadimos los elementos de un diccionario a otro futbolistas.update(suplentes): 
{1: 'Casillas', 3: 'Pique', 4: 'Marchena', 5: 'Puyol', 6: 'Iniesta', 7: 'Villa', 8: 'Xavi Hernandez', 9: 'Torres', 10: 'Cesc', 11: 'Capdevila', 12: 'Valdes', 13: 'Mata', 14: 'Xabi Alonso', 15: 'Ramos', 16: 'Busquets', 17: 'Arbeloa', 18: 'Pedrito', 19: 'Llorente', 20: 'Javi Martinez', 21: 'Silva', 23: 'Reina'}

These have been the most important methods for handling dictionaries in Python. Below is the full code we’ve been breaking down in this tutorial:

# -*- coding: utf-8 -*-
__author__ = 'Richard'

# Defino la varible 'futbolistas' como un diccionario. No es necesario declarar que tipo de dato es
futbolistas = dict()

futbolistas = {
    1 : "Casillas", 15 : "Ramos",
    3 : "Pique", 5 : "Puyol",
    11 : "Capdevila", 14 : "Xabi Alonso",
    16 : "Busquets", 8 : "Xavi Hernandez",
    18 : "Pedrito", 6 : "Iniesta",
    7 : "Villa"
}

# Recorrer un diccionario, imprimiendo su clave-valor
for k,v in futbolistas.items():
    print "%s -> %s" %(k,v)

# Vemos cuantos elementos tiene nuestro diccionario
numElem = len(futbolistas)
print "\nNumero de elementos del diccionario len(futbolistas) = %i" %numElem

# Imprimimos una lista con las claves del diccionario
keys = futbolistas.keys();
print "\nClaves del diccionario futbolistas.keys(): \n%s" %keys

# Imprimimos en una lista los valores del diccionario
values = futbolistas.values()
print "\nValores del diccionario futbolistas.values(): \n%s" %values

# Obtenemos el valor de un elemento dada su clave
elem = futbolistas.get(6)
print "\nObtenemos el valor cuya clave es '6' futbolistas.get(6): %s" %elem

# Insertamos un elemento en el array. Si la clave ya existe no inserta el elemento
elem2 = futbolistas.setdefault(10,'Cesc')
print "\nInsertamos un elemento en el diccionario. Si la clave existe no lo inserta" \
      "\nfutbolistas.setdefault(10,'Cesc'): %s" %elem2

# Añadimos un nuevo elemento a la lista
futbolistas[22] = 'Navas'
print "\nDiccionario tras añadir un elemento: futbolistas[22] = 'Navas' \n%s" %futbolistas

# Eliminamos un elemento del diccionario dada su clave
futbolistas.pop(22)
print "\nDiccionario tras eliminar un elemento: futbolistas.pop(22) \n%s" %futbolistas

# Hacemos una copia del diccionario
futbolistasCopy = futbolistas.copy();
print "\nRealizamos una copia del diccionario futbolistasCopy=futbolistas.copy(): \n%s" %futbolistas

# Eliminamos los elementos de un diccionario
futbolistasCopy.clear()
print "\nEliminamos los elementos de un diccionario futbolistasCopy.clear(): %s" %futbolistasCopy

# Creamos un diccionario a partir de una lista con las claves
keys = ['nombre', 'apellidos', 'edad']
dictList = dict.fromkeys(keys, 'nada')
print "\nCreamos un diccionario a partir de una lista dictList = dict.fromkeys(keys, 'nada'): \n%s" %dictList

# Comprobamos si existe o no una clave
exit2 = futbolistas.has_key(2)
exit8 = futbolistas.has_key(8)
print "\nComprobamos si existen los elementos 2 y 8 \n\tfutbolistas.has_key(2) = %s " \
      "\n\tfutbolistas.has_key(8) = %s" %(exit2,exit8)

# Devolvemos los elementos del diccionario en tuplas
tuplas = futbolistas.items()
print "\nPasamos el diccionario a tuplas con clave-valor: tuplas = futbolistas.items() \n%s" %tuplas

# Mergeamos dos diccionarios
suplentes = {
    4:'Marchena', 9:'Torres', 12:'Valdes',
    13:'Mata' , 17:'Arbeloa', 19:'Llorente',
    20:'Javi Martinez', 21:'Silva', 23:'Reina'
}

futbolistas.update(suplentes)
print "\nAñadimos los elementos de un diccionario a otro futbolistas.update(suplentes): \n%s" %futbolistas

“Python Dictionary, with Examples” by Ricardo Moya at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ricardo Moya

I work in Machine Learning and Big Data. I like learning new technologies and explaining them as clearly as I can on this site.

You may also like

Python Lists, with Examples

Lists in Python are a data structure that stores an ordered collection of items, which don't have to be of the same type. Learn how to use them with examples.

Apr 6, 2015

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.