---
jupytext:
  formats: content_md///md:myst,content///ipynb
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.13.8
kernelspec:
  display_name: Python 3 (ipykernel)
  language: python
  name: python3
---

(python:lists-friends:dicts)=
# Dictionaries

Dictionaries are like lists, but indices (here denoted as *keys*) are not restricted to integers but can be of any immutable type. Even tuples are allowed as keys if they do not contain mutable items. Data types for keys can be mixed. Type name for dictionaries is `dict`.

## Creating Dictionaries

Dictionary items are defined as colon separated pairs `key: value`.

```{code-cell} ipython3
person = {'name': 'John', 'surname': 'Doe', 'age': 42}
print(person['name'])

person['age'] += 1
print(person['age'])
```

To add data to an existing dictionary simply assign to the new key:

```{code-cell} ipython3
person['gender'] = 'male'
```

With `{}` we obtain an empty dictionary.

## Dictionary Methods

Items may be removed with `del(key)`, like for lists.

The `keys` method returns a list-like object containing all keys used in the dictionary. Similarly, the `values` method returns all values in the dictionary and the `items` method returns all pairs (tuples) of keys and corresponding items.

```{note}
Python follows the [duck typing](https://en.wikipedia.org/wiki/Duck_typing) approach: If it looks like a duck, walks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

In other words: There are many object types in Python which behave like a list, but aren't of type `list`. In particular, `len` and indexing syntax `[...]` may be used for such objects.
```
