# Python learning notes - Dictionary

The dictionary is a bit like the structure in C in function

### A simple dictionary

Look at an example. A dictionary contains some aliens. These aliens have different colors and points.

```alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
```

### Second, use a dictionary

In Python, a dictionary is a series of key value pairs. Each key is associated with a value. We can use the key to access the associated value. The key can be related to numbers, strings, lists and even dictionaries.

#### 1. Access the values in the dictionary

You can specify the dictionary name and the key in square brackets

```alien_0={'color':'green','points':5}
print(alien_0['color'])
```

You can also take an intermediate variable:

```alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
```

#### 2. Add key value pair

A dictionary is a dynamic structure in which key value pairs can be added at any time.
For example, we need to know the location of the alien:

```alien_0={'color':'green','points':5}
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
```

Output results:
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

#### 3. Create an empty dictionary first

We can create an empty dictionary first, and then add key value pairs separately. Such as:

```alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = '5'
print(alien_0)
```

Output results;
{'color': 'green', 'points': '5'}

#### 4. Modify the value in the dictionary

To modify the value in the dictionary, you can know the dictionary name, enclose the specified key in square brackets, and assign the associated new value

```alien_0={'color':'green','points':5}
print(alien_0)
alien_0['color'] = 'yellow'
print(alien_0)
```

Let's take a more complex example:

```alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position: " + str(alien_0['x_position']))

#Move aliens to the right
#The speed of an alien determines how far it moves
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:#The alien moves very fast
x_increment = 3

alien_0['x_position'] = alien_0['x_position'] + x_increment
print('Now x_position:' + str(alien_0['x_position']))
```

We can determine the value for alien movement through the if statement

#### 5. Delete key value pair

For values that are no longer needed in the dictionary, you can use the del statement to completely delete the corresponding value key

```alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

del alien_0['points']
print(alien_0)
```

Note: deleted values are permanently lost

#### 6. Dictionary composed of similar objects

A dictionary can store not only a variety of information about an object, but also information about different objects. The example stores the programming languages that different people like to use:

```favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Phili's faorite language is "+favorite_languages['jen'].title())
```

### Three traversal dictionary

#### 1. Traverse all key value pairs

First: to write a for loop that can traverse the dictionary, you should first declare two variables: one represents the key and the other represents the value
Note that these two variables can represent any value
Second: the dictionary name and method items(), which returns a list of key values. Next, the for loop stores each value in the specified two variables at a time.
Note: even when traversing the dictionary, the return order of key value pairs is different from the storage order. Python does not care about the storage order of key value pairs, but only tracks the correlation between keys and values.

```user_0 = {
'first': 'enrico',
'last': 'fermi',
}

for key,value in user_0.items():
print('\nKey',key)
print('\nValue',value)
```
##### 2. Traverse all values in the dictionary

When the value in the experimental dictionary is not needed, the method key() can print all key names

```favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

for name in favorite_languages.keys():
print(name.title());
```

Here is a slightly more complex example. We can add some operations on the basis of traversal:

```favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

friends = ['jen','phil']
for name in favorite_languages.keys():
print(name.title());
if name in friends:
print(name+"'s favorite language is "+favorite_languages[name].title()+"!")
```

keys() is not only used for traversal; In fact, it can return a list containing all the keys in the dictionary.

#### 3. Traverse all keys in the dictionary in order

Usually, when we get the elements of the dictionary, the order of acquisition is unpredictable. We can use the function sorted() to get a copy of the list in a specific order.

```favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
```

#### 4. Traverse all values in the dictionary

We can use the method values(), which returns a list of values without any keys.
For example:

```favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
```

When our project has duplicates, we can use the set(), each of which takes a unique value:

```favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
```

### Four nesting

Sometimes, we need to store some lists in dictionaries, or store some dictionaries in lists, which is nesting.

#### 1. Dictionary list

Our allen can only store the information of one alien, not three at the same time. Example:

```alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}

aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
```

More realistically, there are more than three aliens, and each is randomly generated. At this time:

```aliens = []

for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)

for alien in aliens[:5]:
print(alien)

print("Total number of aliens is "+str(len(aliens)))
```

If we need to change the first three aliens to yellow, the speed becomes medium and the value is ten points:

```aliens = []

for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)

for alien in aliens[0:3]:#A dictionary is a dictionary
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 10
alien['speed'] = 'medium'

for alien in aliens[0:5]:
print(alien)

print("Total number of aliens is "+str(len(aliens)))
```

We can further expand the program, such as using elif to change the Yellow alien to red and so on

#### 2. Store list in dictionary

When we need to associate a key with multiple associated words, we can use nesting:

```pizzas = {
'crust':'thick',
'toppings':['mushrooms','extra chess']
}

print("you want a"+pizzas['crust']+"-crust pizza")
print("wint toppings:")
for topping in pizzas['toppings']:
print("\t"+topping)
```

#### 3. Store the dictionary in the dictionary

For example, we need to list several different users and store their personal information. In this case, the dictionary should be stored in the dictionary;

```users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}