Python dictionary application and related operations!

How does Xiaobai become a python data analyst

Day 9 ----- > Dictionary (dict)

In primary school, we learned to look through the Xinhua dictionary. We can query the word we are looking for through the directory index, so as to understand and learn the word and its meaning. So what about the data types we like dictionaries in programming languages? Yes, it's also called a dictionary. Just as in Xinhua Dictionary, every word has its corresponding interpretation, each word and its interpretation together is an entry in the dictionary. In the dictionary, a word is called a key, and the interpretation of a word is called a value. An entry consisting of a key and a value is called a key value pair. Dictionary = {key: value, key: value, key: value,...}

When we need to store multiple information, such as a person's personal information (name, age, gender, hobbies, contact method...), we can use the lists, tuples and collections we have learned before, but you will find that these are not the best choice. There will be their own problems. When we put a pile of data in and read the data, we will find out, what is this? Because there is no statement, we don't know the data we put in when we read it out. Collection is the most inappropriate because it has weight removal characteristics. If a person's age and weight are the same, there will be less information in the collection. When querying, we need to know the subscript to find it. Otherwise, you have to search one by one, which is inefficient. Then the dictionary saved us.

We can well understand the meaning of (value) data through keys, and we can quickly query the value through keys.

dictionary type, which is most suitable for assembling associated information, and can help us solve the problem of modeling real things in programs.

I believe you have a certain understanding of the dictionary. Let's study the dictionary more deeply!

Create and use dictionaries

1. Literal grammar

Creating dictionaries in Python can use {} literal syntax, which is similar to lists and collections. It is worth noting that the elements in {} of the dictionary exist in the form of key value pairs. Each element consists of two separated values: the key in front and the value in the back.

kuanglu = {
    'Li Chungang': 'Heaven doesn't give birth to me, Li Chungang. Kendo is like a long night.',
    'Xiao Yan': 'Thirty years east of the river, thirty years west of the river, don't bully the young poor!',
    'An LAN': 'The top of the immortal, proud of the world, with me, Anlan will have a day!',
    'Wang Teng': 'My son Wang Teng looks like a great emperor!'

}
print(kuanglu['Wang Teng'])

person = {
    'name': 'Da Chui Wang',
    'age': 20,
    'weight': 60,
    'office': '62 Kehua North Road',
    'home': 'No. 8, zhongtongren Road',
    'tel': '13122334455',
    'contacts': {
        'qq': 123456,
        'tel': 12345678910,
        'a': 45,
        '9': 58
    }
}
print(person['name'])
print(person['contacts']['qq'])
print(person['contacts']['a'])
print(person['contacts']['9'])

Using a dictionary to save a person's information is far better than using a list or tuple, because we can use the front key to represent the meaning of the entry, and the back is the value corresponding to the entry.

2. Constructive syntax (use the built-in function dict to create a dictionary)

# Each set of parameters in the dict function (constructor) is a set of key value pairs in the dictionary
person = dict(name='An LAN', age=99999999, weight=9999999, home='Imperial City')
print(person)    # {name = 'Anlan', age = 9999999, weight = 9999999, home = 'Imperial City'}

3. zip the two sequences through Python's built-in function and create a dictionary

a = 'ABCDE'
b = '12345'
items1 = dict(zip(a, b))
# 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}

4. Create dictionary with generative grammar

# Generative syntax for lists
list1 = [i for i in range(1, 10)]
print(list1)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Generative grammar of dictionary
student2 = {i: i ** 2 for i in range(1, 10)}
print(student2) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}


5. Loop through the dictionary

If you want to know how many key value pairs there are in the dictionary, you still use the len function; If you want to traverse the dictionary, you can use the for loop, but note that the for loop only traverses the keys of the dictionary

student = {'name': 'An LAN',
           'age': 99999,
           'weight': 9999999,
           'office': 'Perfect World',
           'home': 'Tianyuan primitive Imperial City',
           'tel': 'Call my real name',}
print(len(student))    # 6



# Key to traverse the dictionary
for key in student.keys():
    print(key, student[key])
    # print(key)
print('-' * 10)
# Traverse dictionary values
for value in student.values():
    print(value)
print('-' * 10)
# Traversal key queue
for key, value in student.items():
    print(key, value)
print('-' * 10)


Dictionary operation

For dictionary types, member operation and index operation are certainly the most important. The former can determine whether the specified key is in the dictionary, and the latter can obtain the corresponding value through the key or add a new key value pair to the dictionary.

Note: the index of the dictionary is different from the index of the list. Because the elements in the list have their own sequence number (subscript), 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.

The dictionary also uses hash storage, so 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;

Lists 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.

person = {
    'name': 'An LAN',
    'age': 99999,
    'weight': 9999999,
    'office': 'Perfect World',
    'home': 'Tianyuan primitive Imperial City',
    'tel': 'Call my real name'
}
# Check whether the name and tel keys are in the person dictionary
print('name' in person, 'tel' in person)    # True False
# Modify the corresponding value in the person dictionary to 250 through age modification
if 'age' in person:
    person['age'] = 250
print(person)
# Store a new key value pair into the person dictionary through the index operation
person['tel'] = '13122334455'
person['signature'] = 'Even if I carry the abyss, I need to hold the original imperial city with one hand. I am as invincible as Anlan in the world!'

# Check the number of key value pairs in the person dictionary
print(len(person))    # 7
# Get the corresponding key pass value of the dictionary and perform cyclic key pass operation
for key in person:
    print(f'{key}: {person[key]}')

It should be noted that when obtaining the value in the dictionary through index operation, if the specified key is not in the dictionary, a KeyError exception will be thrown. At this time, we can use the get function to obtain the value through the key. If the key does not exist, it returns a null value without an error.

# When using the get function to obtain value through key, if the key does not exist, a null value will be returned and no error will be reported.
print(student.get('name'))
print(student.get('bgy'))

Dictionary method

# The value in the dictionary is another dictionary (nested Dictionary)
students = {
    1001: {'name': 'Di Renjie', 'sex': True, 'age': 22, 'place': 'Datong, Shanxi'},
    1002: {'name': 'Bai Yuanfang', 'sex': True, 'age': 23, 'place': 'Baoding, Hebei'},
    1003: {'name': 'Wu Zetian', 'sex': False, 'age': 20, 'place': 'Guangyuan, Sichuan'}
}

# Use the get method to obtain the corresponding value through the key. If it cannot be obtained, the KeyError exception will not be raised, but None or the set default value will be returned
print(students.get(1002))    # {'name': 'Bai Yuanfang', 'sex': True, 'age': 23, 'place': 'Baoding, Hebei'}
print(students.get(1005))    # None
print(students.get(1005, {'name': 'anonymous person'}))    # {'name': 'anonymous'}

# Gets all keys in the dictionary
print(students.keys())      # dict_keys([1001, 1002, 1003])
# Gets all the values in the dictionary
print(students.values())    # dict_values([{...}, {...}, {...}])
# Gets all key value pairs in the dictionary
print(students.items())     # dict_items([(1001, {...}), (1002, {....}), (1003, {...})])
# Loop through all key value pairs in the dictionary
for key, value in students.items():
    print(key, '--->', value)

# Use the pop method to delete the corresponding key value pair through the key and return the value
stu1 = students.pop(1002)
print(stu1)             # {'name': 'Bai Yuanfang', 'sex': True, 'age': 23, 'place': 'Baoding, Hebei'}
print(len(students))    # 2
# stu2 = students.pop(1005)    # KeyError: 1005
stu2 = students.pop(1005, {})
print(stu2)             # {}

# Use the popitem method to delete the last set of key value pairs in the dictionary and return the corresponding binary
# If there is no element in the dictionary, calling this method will throw a KeyError exception
key, value = students.popitem()
print(key, value)    # 1003 {'name': 'Wu Zetian', 'sex': False, 'age': 20, 'place': 'Guangyuan, Sichuan'}

# setdefault can update the value corresponding to the key in the dictionary or store a new key value pair in the dictionary
# The first parameter of the setdefault method is the key, and the second parameter is the value corresponding to the key
# If the key exists in the dictionary, the original value corresponding to the key will be returned after updating the key
# If this key does not exist in the dictionary, the method will return the value of the second parameter, which defaults to None
result = students.setdefault(1005, {'name': 'Fang Qihe', 'sex': True})
print(result)        # {'name': 'Fang Qihe', 'sex': True}
print(students)      # {1001: {...}, 1005: {...}}

# Use update to update dictionary elements. The same key will overwrite the old value with the new value, and different keys will be added to the dictionary
others = {
    1005: {'name': 'Qiao Feng', 'sex': True, 'age': 32, 'place': 'Beijing Daxing'},
    1010: {'name': 'Wang Yuyan', 'sex': False, 'age': 19},
    1008: {'name': 'Zhong Ling', 'sex': False}
}
students.update(others)
print(students)      # {1001: {...}, 1005: {...}, 1010: {...}, 1008: {...}}

Like the list, the del keyword can also be used to delete an element from the dictionary. When deleting an element, if the specified key index does not find the corresponding value, the KeyError exception will be thrown. The specific methods are as follows.

dict1 = {'a': 100, 'b': 200, 'c': 300}
dict2 = {'d': 400, 'e': 500, 'f': 600, 'a': 250}

# Update (merge)
dict1.update(dict2)
print(dict1)

# The delete - > key must exist. If it does not exist, a keyerror will be generated
# del dict1['b']
# print(dict1)
print(dict1.pop('b'))


# Delete end key
dict2.popitem()

Application of dictionary

Case:

1. Enter a paragraph and count the number of occurrences of each English letter.

# 1. Enter a paragraph and count the number of occurrences of each English letter.
# Method 1

import string
# Generate lower case Dictionary: {0}
results = {letter: 0 for letter in string.ascii_lowercase}
# print(results) 
content = input('Please enter: ').lower()  # . lower() converts the English in the input string to English lowercase.
# Traverses the elements of the loop input
for ch in content:
    # If there are elements in the dictionary results
    if ch in results:
        #Value plus 1
        results[ch] += 1
# print(results)
# Loop to get the key and value of dictionary results
for key, value in results.items():
    print(f'{key}: {value:>2d}second')
    
# Method 2
sentence = input('Please enter a paragraph: ')
counter = {}
for ch in sentence:
    if 'A' <= ch <= 'Z' or 'a' <= ch <= 'z':
        counter[ch] = counter.get(ch, 0) + 1
for key, value in counter.items():
    print(f'letter{key}There it is{value}second.')


2. Enter a paragraph and count the number of occurrences of each English word.

# 2. Enter a paragraph and count the number of occurrences of each English word.

content = input('Please enter: ').replace(',', ' ')  # Convert "," in the input string to spaces. Easy to split later
content_now = content.split(' ')  # Split by space
results = {letter: 0 for letter in content_now}  # Build dictionary
for word in content_now:
    if word in results:
        results[word] += 1
print(results)
for key, value in results.items():
    print(f'{key}:{value}second')

3. Save the stock code and price in a dictionary, find out the stocks with a stock price greater than 100 yuan, and create a new dictionary.

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

# Method 1
for key, value in stocks.items():
        if value > 100:
         dict1[key] = value
print(dict1)
# Generative syntax creation of dictionary
dict2 = {key: value for key, value in stocks.items() if value > 100}
print(dict2)


# Find the name of the stock with the largest share price and the smallest share price,
# Using the max function, note that the functions Max and min compare the size of the key by default. So we need to specify the comparison method "kry"=“
# Method 1 Find maximum, minimum
print(max(stocks, key=stocks.get)) # Find the maximum and press the specified value
print(min(stocks, key=stocks.get))


# Method 2

# You can use Python's built-in function zip to compress two sequences and create a dictionary. Using this function, we transpose keys and values,
dict4 = dict(zip(stocks.values(), stocks.keys()))
print(dict4)

# Maximum and minimum keys.
# The key and value are transposed with each other. The comparison is the key (stock price) and the output value (stock name) [1]
print(max(zip(stocks.values(), stocks.keys()))[1])
print(min(zip(stocks.values(), stocks.keys()))[1])
# Decomposition action
_, max_values = max(zip(stocks.values(), stocks.keys()))
print(max_values)


# Stock prices are sorted from large to small
# Dictionary sort, sorted()
print(sorted(stocks, key=stocks.get, reverse=True))

Keywords: Python

Added by Static_Nexus on Wed, 05 Jan 2022 05:04:10 +0200