Python learning notes: 12 container data types ----- dictionary

Cognitive dictionary

  1. Dictionaries
  • The dictionary is a container data type. It takes {} as the flag of the container. The elements in the dictionary are key value pairs, such as: {key 1: value 1, key 2: value 2, key 3: value 3,...}
  • The dictionary is variable (addition, deletion and modification are supported)
  • The dictionary is out of order (subscript operation is not supported)
  1. Dictionary element (key value pair)
  • All elements in the dictionary must be key value pairs, and keys and values must appear in pairs; Dictionaries store values, and keys are used to distinguish and explain different values.
  • Key: any immutable data can be used as a key. In actual development, the string is generally used as a key; Key is unique.
  • Value: any type of data can be used as the value of the dictionary.

Create and use dictionaries

There are three ways to create a dictionary

# literal syntax 
student1 = {
    'id': 1001,
    'name': 'indigo plant',
    'sex': 'female',
    'birthday': '1999-07'
}
print(student1)
# Constructor function
student2 = dict(id=1002, name='Xiaobai', sex='female', birthday='2000-01')
print(student2)

# Generative Grammar (deductive grammar)
dict1 = {i: i ** 2 for i in range(1, 9)}
print(dict1)

Operation results:

{'id': 1001, 'name': 'indigo plant', 'sex': 'female', 'birthday': '1999-07'}
{'id': 1002, 'name': 'Xiaobai', 'sex': 'female', 'birthday': '2000-01'}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

There is also a common method of creating a dictionary, which compresses lists and strings, lists and lists, strings and strings, and creates a dictionary.

# You can zip two sequences and create a dictionary through Python's built-in function
items1 = dict(zip('ABCDE', '12345'))
print(items1)    # {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5'}
items2 = dict(zip('ABCDE', range(1, 10)))
print(items2)    # {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}

list1 = [1, 2, 3]
str1 = 'hello'
list2 = ['xx', 'yy', 'zz']
print(dict(zip(str1, list1)))      # {'h': 1, 'e': 2, 'l': 3} 
print(dict(zip(list2, list1)))     # {'xx': 1, 'yy': 2, 'zz': 3}

Traversal list

student1 = {
    'id': 1001,
    'name': 'indigo plant',
    'sex': 'female',
    'birthday': '1999-07'
}
# Loop traversal
# Traverse keys in the dictionary
for key in student1:
    print(key, student1[key])
print('-' * 20)
# Traverse keys in the dictionary
for key in student1.keys():
    print(key, student1[key])
print('-' * 20)
# Traverse the values in the dictionary
for value in student1.values():
    print(value)
print('-' * 20)
# Traverse key value pairs in the dictionary
for key, value in student1.items():
    print(key, value)

Operation results:

id 1001
name indigo plant
sex female
birthday 1999-07
--------------------
id 1001
name indigo plant
sex female
birthday 1999-07
--------------------
1001
 indigo plant
 female
1999-07
--------------------
id 1001
name indigo plant
sex female
birthday 1999-07

Dictionary operation

  1. The member operation can determine whether the specified key is in the dictionary. The index operation can obtain the corresponding value through the key or add a new key value pair to the dictionary. It is worth noting that the index of the dictionary is different from the index of the list. Because the elements in the list have their own serial numbers, the index of the list is an integer; Because key value pairs are saved in the dictionary, the index of the dictionary is the key in the key value pair. The original value can be modified or a new key value pair can be stored in the dictionary through index operation.

  2. The keys in the dictionary must be immutable types, such as integer (int), floating point number (float), string (str), tuple and other types of values; Obviously, list s and set s cannot be used as keys in dictionaries. Of course, dictionary types can no longer be used as keys in dictionaries, because dictionaries are also variable types, but dictionaries can be used as values in dictionaries.

student = dict(id=1002, name='Xiaobai', sex='female', birthday='2000-01')
# Member operation
print('name' in student)                  # True
print('age' in student)                   # False
print('address' not in student)           # True

# Index operation
# The index operation of the dictionary is placed to the left of the assignment operator
# If the key corresponding to the index exists in the dictionary, its value is updated
student['name'] = 'Xiaorou'     
# If the key corresponding to the index does not exist in the dictionary, the key value pair is added
student['address'] = 'Chengdu, Sichuan'
print(student)              # {'id': 1002, 'name': 'xiaorou', 'sex': 'female', 'birthday': '2000-01', 'address':' Chengdu, Sichuan '}
print(student['birthday'])  # 2000-01
# When using the get function to obtain value through key, if the key does not exist, it returns None
print(student.get('age'))   # None
# If the key does not exist, the specified value is returned
print(student.get('age', 20))  # 20
# Delete key value pair
print(student.pop('id'))       # 1002
del student['name']

print(student)            # {'sex': 'female', 'birthday': '2000-01', 'address':' Chengdu, Sichuan '}
print(student.get('name', 'anonymous person'))   # anonymous person

# If you use index operation, you must ensure that the key must exist, otherwise an error will be reported
if 'birthday' in student:
    print(student['birthday'])    # 2000-01
dict1 = {'A': 100, 'B': 200, 'C': 300}
dict2 = {'D': 400, 'E': 500, 'A': 600}
# Update dictionary
dict1.update(dict2)   
print(dict1)       # {'A': 600, 'B': 200, 'C': 300, 'D': 400, 'E': 500}

# The delete -- > key must exist, otherwise KeyError will be generated
del dict1['B']
dict1.pop('C')
print(dict1)      # {'A': 600, 'D': 400, 'E': 500}
# Delete the last key value pair
dict1.popitem()
print(dict1)     # {'A': 600, 'D': 400}
# Empty dictionary
dict1.clear()
print(dict1)     # {}

# If the key exists, the corresponding value is returned. If it does not exist, a new key value pair is added and the corresponding value is returned
print(dict2.setdefault('A'))         # 600
print(dict2.setdefault('K', 1000))   # 1000
print(dict2)        # {'D': 400, 'E': 500, 'A': 600, 'K': 1000}

Application of dictionary

Example 1: enter a paragraph and count the number of occurrences of each English letter.

import string
str1 = input()
# English letter to lowercase
str1 = str1.lower()
# Generates a dictionary consisting of 26 lowercase English letters with a value of 0
dict_str = {letter: 0 for letter in string.ascii_lowercase}
# Count the number of occurrences of each English letter
for s in str1:
    if s in dict_str:
        dict_str[s] += 1
for letter, count in dict_str.items():
    print(f'{letter}: {count}')

Call ASCII in string Library_ Lowercase variable can get 26 lowercase English letters.

Example 2: save the stock code and price in a dictionary, find out the stocks with a stock price greater than 100 yuan, create a new dictionary, find the stock code corresponding to the stocks with the highest and lowest price, and sort the stock codes according to the stock price from high to low

stocks = {
    'AAPL': 191.88,
    'GOOG': 1186.96,
    'IBM': 149.24,
    'ORCL': 48.44,
    'ACN': 166.89,
    'FB': 208.09,
    'SYMC': 21.29
}

stocks1 = {k: v for k, v in stocks.items() if v > 100}
print(stocks1)   # {'AAPL': 191.88, 'GOOG': 1186.96, 'IBM': 149.24, 'ACN': 166.89, 'FB': 208.09}
# zip can compress two lists into several tuples
print(max(zip(stocks.values(), stocks.keys()))[1])   # GOOG
print(min(zip(stocks.values(), stocks.keys()))[1])   # SYMC

# Find the maximum by value and return the key corresponding to the maximum value
print(max(stocks, key=stocks.get))         # GOOG
# Find the minimum by value and return the key corresponding to the minimum value
print(min(stocks, key=stocks.get))         # SYMC
# Sort by value and return an ordered list. reverse = True indicates descending order
print(sorted(stocks, key=stocks.get, reverse=True))  # ['GOOG', 'FB', 'AAPL', 'ACN', 'IBM', 'ORCL', 'SYMC']

Keywords: Python

Added by nickholt1972 on Tue, 04 Jan 2022 14:45:26 +0200