# Python Dictionaries

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable, and does not allow duplicates.

*Note: As of Python 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.*

## Creating a Dictionary

Dictionaries are written with curly brackets, and have keys and values.

```python
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)
```

## Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets.

```python
x = thisdict["model"]
```

There is also a method called `get()` that will give you the same result:

```python
x = thisdict.get("model")
```

## Modifying Dictionaries

### Change Values

You can change the value of a specific item by referring to its key name.

```python
thisdict["year"] = 2018
```

### Add Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it.

```python
thisdict["color"] = "red"
```

### Remove Items

The `pop()` method removes the item with the specified key name.

```python
thisdict.pop("model")
```

## Loop Through a Dictionary

You can loop through a dictionary by using a `for` loop.

```python
# Print all key names
for x in thisdict:
  print(x)

# Print all values
for x in thisdict:
  print(thisdict[x])

# Loop through both keys and values
for key, value in thisdict.items():
  print(key, value)
```

[[programming/python/python]]