current position:Home>11 "Python dictionary" knowledge points easy to use

11 "Python dictionary" knowledge points easy to use

2022-02-02 07:40:09 jiejie

Hello everyone , I am a Jiejie

About Python Dictionaries , Count as Python A very important data type in . After you learn the basics , The concept of dictionary , It will accompany your later study and work . therefore , Here are some very important knowledge points , You need to know .

Whether the dictionary is out of order

About this concept , Many friends don't necessarily know . stay Python 2.7 in , Dictionaries are disordered structures . The order of dictionary items is chaotic . This means that the sequence of projects is deterministic and repeatable .

>>> # Python 2.7
>>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> a_dict
{'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
>>> a_dict
{'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
 Copy code 

stay Python 3.5 in , The dictionary is still out of order , But this time it's a random data structure . This means that every time you rerun the dictionary , You will get different project orders .

>>> # Python 3.5
>>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> a_dict
{'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
>>> a_dict
{'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
 Copy code 

stay Python 3.6 And later , A dictionary is an ordered data structure , This means that they keep the order of elements the same as when they were introduced .

>>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> a_dict
{'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> a_dict
{'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
 Copy code 

Key exchange

Suppose you have a dictionary , For some reason, you need to convert keys to values , Values are converted to keys , What should be done ?

>>> a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
>>> new_dict = {}
>>> for key, value in a_dict.items():
...     new_dict[value] = key
...
>>> new_dict
{1: 'one', 2: 'two', 3: 'thee', 4: 'four'}
 Copy code 

Under certain conditions , Filter dictionary occasionally , You need to filter the dictionary according to certain conditions . So match if Conditional statements , Is a good choice .

>>> a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
>>> new_dict = {}  # Create a new empty dictionary
>>> for key, value in a_dict.items():
...     if value <= 2:
...         new_dict[key] = value
...
>>> new_dict
{'one': 1, 'two': 2}
 Copy code 

Use the values in the dictionary , Do some calculations stay Python When traversing the dictionary . It's also common to do some calculations . Suppose you have stored the data of your company's sales in a dictionary , Now you want to know the total income of a year .

>>> incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
>>> total_income = 0.00
>>> for value in incomes.values():
...     total_income += value  # Accumulate the values in total_income
...
>>> total_income
14100.0
 Copy code 

Dictionary derivation

Dictionary derivation , Is the same as the list derivation , Knowledge points with powerful functions . therefore , You must master . for example , Suppose you have two data lists , You need to create a new dictionary based on them .

>>> objects = ['blue', 'apple', 'dog']
>>> categories = ['color', 'fruit', 'pet']
>>> a_dict = {key: value for key, value in zip(categories, objects)}
>>> a_dict
{'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
 Copy code 

Use the dictionary to deduce , Implement key value conversion

You'll find that , Use dictionary derivation , It's a simpler 、 Efficient operation .

>>> a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
>>> new_dict = {value: key for key, value in a_dict.items()}
>>> new_dict
{1: 'one', 2: 'two', 3: 'thee', 4: 'four'}
 Copy code 

Use the dictionary to deduce , Filter dictionary

>>> a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
>>> new_dict = {k: v for k, v in a_dict.items() if v <= 2}
>>> new_dict
{'one': 1, 'two': 2}
 Copy code 

Use the dictionary to deduce , Do some calculations

>>> incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
>>> total_income = sum([value for value in incomes.values()])
>>> total_income
14100.0
 Copy code 

Dictionary sort

from Python 3.6 Start , A dictionary is an ordered data structure , So if you use Python 3.6( And higher ), You will be able to use sorted() And understand the keys to any dictionary with the help of a dictionary , Sort .

>> incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
>>> sorted_income = {k: incomes[k] for k in sorted(incomes)}
>>> sorted_income
{'apple': 5600.0, 'banana': 5000.0, 'orange': 3500.0}
 Copy code 

Built in functions , Use with a dictionary

Python Some built-in functions are provided , These functions are used when you are dealing with collections ( Such as a dictionary ) It can be useful .

map() function

Suppose you have a dictionary containing a bunch of product prices , And you need to apply discounts to them .

>>> prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25}
>>> def discount(current_price):
...     return (current_price[0], round(current_price[1] * 0.95, 2))
...
>>> new_prices = dict(map(discount, prices.items()))
>>> new_prices
{'apple': 0.38, 'orange': 0.33, 'banana': 0.24}
 Copy code 

filter() function

Suppose you want to know that the unit price is lower than 0.40 Products .

>>> prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25}
>>> def has_low_price(price):
...     return prices[price] < 0.4
...
>>> low_price = list(filter(has_low_price, prices.keys()))
>>> low_price
['orange', 'banana']
 Copy code 

Dictionary unpacking operator

This is a concept that many people don't know ,Python 3.5 Brings an interesting new feature , Therefore, we need to focus on learning . You can use the dictionary unpacking operator ( **) Merge the two dictionaries into a new dictionary .

>>> vegetable_prices = {'pepper': 0.20, 'onion': 0.55}
>>> fruit_prices = {'apple': 0.40, 'orange': 0.35, 'pepper': .25}
>>> {**vegetable_prices, **fruit_prices}
{'pepper': 0.25, 'onion': 0.55, 'apple': 0.4, 'orange': 0.35}
 Copy code 

If you try to merge dictionaries , Having duplicate or common keys , Then the value of the rightmost dictionary will be supplemented by .

If you think this article , If it's of some use to you , Remember, don't forget 3 even , Your affirmation will be the strongest driving force for me to continue to output more high-quality articles !

copyright notice
author[jiejie],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020740068632.html

Random recommended