Skip to content

Python Dictionary Basics

The Python Dictionary is used to store key-value pairs in a variable. It is one of a total of four data structures that are pre-installed in Python. In addition to the dictionary, these also include the tuple, the set, and the list.

We define a Python dictionary by writing the key-value pair in curly braces and separated by a colon. We can store elements with different data types in a dictionary.

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000
}

# Query the population
print(this_city['population'])

Out: 
3645000

We can query the elements of the dictionary by specifying the key in square brackets. Then we get the corresponding value stored for this key.

Basic Properties

Since Python version 3.7 the dictionary is ordered. This means that the order in which we store the key-value pairs also plays a role. In the versions before that, in contrast, the order has no meaning. In addition, the Python dictionary is also modifiable, i.e. after it has been created, elements can be changed, added, or deleted from the dictionary.

The most important feature of the dictionary is that duplicate key-value pairs are not allowed. In other data formats in Python, however, duplicate elements are allowed. If we want to add a key-value pair to the dictionary whose key already exists, the old pair is overwritten without notification.

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000
}

# Set new value for the key 'country'
this_city['country'] = 'France'

# Query the country
print(this_city['country'])

Out: 
'France'

Query Elements

There are various information and elements that we can query from a dictionary.

As we have already seen, we can query the value by defining the associated key in square brackets. Similarly, the “get()” method returns the same result:

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000
}

# Get value of key 'country'
print(this_city['country'])
print(this_city.get('country'))

Out:
'Germany'
'Germany'

With the commands “.keys()” and “.values()” Python returns us a list of all keys and values. The order of the lists also corresponds to how they are stored in the dictionary. This also means that the list of values may contain duplicates.

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000,
    'country_2': 'Germany'
}

# Get list of all keys
print(this_city.keys())
# Get list of all values
print(this_city.values())

Out:
dict_keys(['city', 'country', 'population', 'country_2'])
dict_values(['Berlin', 'Germany', 3645000, 'Germany'])

On the other hand, if we want to retrieve the full key-value pairs, we use the “.items()” method, which returns the pairs as a list of tuples:

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000
}

# Get all key-value pairs
print(this_city.items())

Out:
dict_items([('city', 'Berlin'), ('country', 'Germany'), ('population', 3645000)])

Change Dictionary Elements

If we want to change individual values within the dictionary, we can do this directly via the key. Since there must not be duplicate keys, the old value is simply overwritten. If we want to change multiple pairs at once, we use the “.update()” method and define the new key-value pairs in it.

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000
}

# Change one key-value pair
this_city['city'] = 'Paris'

# Change multiple key-value pairs
this_city.update({'country': 'France', 'population': 2161000})

print(this_city)

Out:
{'city': 'Paris', 'country': 'France', 'population': 2161000}

Delete Elements

If we want to delete a single element from the Python dictionary, we can either specify the key and use the “pop()” method to specifically delete the element, or use “popitem()” to delete the last added key-value pair:

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000
}

# Delete element with key 'population'
this_city.pop('population')
print(this_city)

Out:
{'city': 'Berlin', 'country': 'Germany'}

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000
}

# Delete element with key 'population'
this_city.popitem()
print(this_city)

Out:
{'city': 'Berlin', 'country': 'Germany'}

Finally, you can clear the entire Python dictionary with the “clear()” method:

# Define a dictionary for the city of Berlin
this_city = {
    'city': 'Berlin',
    'country': 'Germany',
    'population': 3645000
}

# Delete element with key 'population'
this_city.clear()
print(this_city)

Out:
{}

Python Collections

In Python, there are a total of four data types that are stored by default:

  • The list is an ordered collection of elements, which is changeable and can also contain duplicate elements.
  • The tuple is in effect a list, with the difference that it is no longer changeable. So no elements can be added or removed afterwards.
  • The set does not allow duplicate entries. At the same time, the arrangement of the elements within the set is variable. The set itself can be changed, but the individual elements cannot be changed afterwards.
  • Since Python version 3.7, a dictionary is an ordered collection of elements that can be changed. In the earlier versions, the dictionary is unordered.

This is what you should take with you

  • The Python Dictionary is one of four pre-installed data structures in Python.
  • It is used to store key-value pairs in a single variable.
  • w3schools offers detailed examples of Python dictionaries with the possibility to execute code snippets directly online.
close
Das Logo zeigt einen weißen Hintergrund den Namen "Data Basecamp" mit blauer Schrift. Im rechten unteren Eck wird eine Bergsilhouette in Blau gezeigt.

Don't miss new articles!

We do not send spam! Read everything in our Privacy Policy.

Tags:
Cookie Consent with Real Cookie Banner