# Dictionaries

A dictionary (or dict) is a collection of key:value pairs. As of Python version 3.7, dictionaries are now ordered by insertion order.

Creating a dictionary

```python
actor = {
    'name': 'John Cleese',
    'funnyAF': True,
    'characters': ['Sir Lancelot', 'The Black Knight', 'Mr. Teabag, The Minister of Silly Walks']
}
```

Accessing values

```python
print(actor['name'])
```

Adding and changing keys

```python
actor['age'] = 82
actor['name'] = 'John Marwood Cleese'
print(actor)
```

#### Dictionary Methods

Dictionaries have a lot of useful methods. Here are a few:

|          |                                                          |
| -------- | -------------------------------------------------------- |
| `get`    | "safely" access a key and optionally set a default value |
| `keys`   | gets a list of all the keys                              |
| `values` | gets a list of all the values                            |
| `items`  | gets a list of key-value pairs as tuples                 |
| `pop`    | remove a key-value pair with the specified key           |

```python
print(actor.get('nationality', 'Earthling')) # -> Earthling
print(actor.keys())
print(actor.values())
print(actor.items())

is_funny = actor.pop('funnyAF')
print(is_funny)
print(actor)
```

Avoid errors when `pop`ping a non-existent key

```python
height = actor.pop('height') # -> KeyError
height = actor.pop('height', None)
print(height) # -> None
```

For more dictionary methods: <https://www.w3schools.com/python/python_ref_dictionary.asp>

**Looping Over Dictionaries**

Dictionaries are iterable with a `for in` loop.

```python
for key in actor:
    print(key)
```

You can also loop over the lists returned by the `keys`, `values`, and `items` methods.

```python
for k, v in actor.items():
    print(f'Key - {k}')
    print(f'Value - {v}')
```

**Dictionary Operators**

The `in` membership operator works with dictionaries.

```python
print('name' in actor)   # -> True
print('height' in actor) # -> False
```

As of Python version 3.9, the `|` operator can merge dictionaries.

```python
a = { 'spam': 3, 'eggs': 2 }
b = { 'bacon': 1, 'sausage': 1, 'spam': 5 }

c = a | b
print(c)
```

*NOTE* `spam` from `b` overwrote the one from `a` as `b` is the "last-seen" value (the right-hand operand).
