# [python notes] 5. Dictionary

Posted by simflex on Wed, 29 Jan 2020 03:38:14 +0100

# 1. Dictionaries

Dictionaries can associate related information

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

output

green
5

# 2. Use a dictionary

A dictionary is a series of key-value pairs, each of which is associated with a value. You can use keys to access the values you want to associate. The values associated with a key value can be numbers, strings, lists, or dictionaries. You can use any object as a value in a dictionary
For example,'color':'green'is a key-value pair, and the simplest dictionary has only one key-value dictionary that can contain any number of key-value pairs.

## 1) Access the values in the dictionary

To get the value associated with the key, specify the dictionary name and the key in square brackets at once
eg1:

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

output

green

eg2:

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

output

You just earned 5 points!

A dictionary can add key-value pairs at any time. To add key-value pairs, you can specify the dictionary name in turn, the keys enclosed in square brackets, and the associated values.
python does not care about the order in which key-value pairs are added, only about the correlation between keys and values
eg1:

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

output

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

eg2:

aline_0 = {}#Create an empty dictionary
aline_0['color'] = 'green'
aline_0['points'] = 5
print (aline_0)

output

{'color': 'green', 'points': 5}

## 3) Modify the values in the dictionary

To modify the values in a dictionary, you can specify the dictionary name in turn, the key enclosed in square brackets, and the new value associated with the key.
eg1:

aline_0 = {'color':'green'}
print("The aline is "+aline_0['color']+'.')
aline_0['color'] = 'yellow'
print("The aline is now "+aline_0['color']+".")

output

The aline is green.
The aline is now yellow.

eg2:

aline_0={'x_position':0, 'y_position':25, 'speed':'medium'}
print("Original x-position " + str(aline_0['x_position']))
if aline_0['speed'] == 'slow':
x_increment = 1
elif aline_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
aline_0['x_position'] = aline_0['x_position'] + x_increment
print("New x_position " + str(aline_0['x_position']))

output

Original x-position 0
New x_position 2

## 4) Delete key-value pairs

Use the del statement to delete the corresponding key-value pair completely, you must specify the dictionary name and the key to delete

aline_0 = {'color':'green', 'points':5}
print(aline_0)
del aline_0['points']
print(aline_0)

output

{'color': 'green', 'points': 5}
{'color': 'green'}

ps: Stores the same information for many objects, (format)

favorite_language = {
'jen': 'python',
'sarch': 'c',
'edward': 'ruby',
'phil': 'python',
}
print(favorite_language)
print("Sarch's favorite language is " +
favorite_language['sarch'].title() +
'.')

# 3. Traversing through a dictionary

## 1) Traverse through all key-value pairs

Using a for loop, the dictionary's item() method returns a list of key-value pairs, each of which is stored in two specified variables in turn by a for loop
eg1:

user_0 = {
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)

output

Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi

Using the appropriate variable names makes it easier to understand the role of loops, such as replacing key s and value s with names and language s
eg2:

favorite_language = {
'jen': 'python',
'sarch': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_language.items():
print(name.title() +
"'s favorite language is " +
language.title() + ".")

output

favorite_language = {
'jen': 'python',
'sarch': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_language.items():
print(name.title() +
"'s favorite language is " +
language.title() + ".")

## 2) Traverse through all keys in the dictionary

Use the key() method in the dictionary to extract all keys from the dictionary and store them in variables
eg:

favorite_language = {
'jen': 'python',
'sarch': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_language.keys():
print(name.title())

output

Jen
Sarch
Edward
Phil

When traversing a dictionary, the dictionary will traverse all keys by default, that is, if the key method is not used in the above example, the result will not change
eg2:

favorite_language = {
'jen': 'python',
'sarch': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_language:
print(name.title())

Output:

Jen
Sarch
Edward
Phil
75 original articles published. 0% praised. 1964 visits

Topics: Python Ruby