You can't help knowing these 11 "Python dictionary" knowledge points

Posted by richardandrewle on Fri, 17 Dec 2021 06:05:23 +0100

The python dictionary is a very important data type in Python. After you learn the basic knowledge, the concept of dictionary will accompany your later study and work.
Therefore, here are some very important knowledge points that we need to know.

1, Is the dictionary out of order

Many friends don't necessarily know about this concept.
In Python 2.7, dictionaries are unordered 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'}

In Python 3.5, the dictionary is still unordered, but this time it is a random data structure. This means that each time you rerun the dictionary, you get a different order of items.

>>> # 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'}

In Python 3.6 and later, dictionaries are ordered data structures, which 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'}

2, Key value exchange

Suppose you have a dictionary. For some reason, you need to convert keys to values and values to keys. What should you do?

>>> 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'}

3, Filter the dictionary according to certain conditions

Sometimes you need to filter the dictionary according to certain conditions. Then it is a good choice to cooperate with if conditional statements.

>>> 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}

4, Use the values in the dictionary to do some calculations

When traversing the dictionary in Python. It is also common to need some calculations. Suppose you have stored the data of the company's sales in the dictionary, and now you want to know the total revenue 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

5, Dictionary derivation

Dictionary derivation is a very powerful knowledge point like list derivation. Therefore, we must master.
For example, suppose you have two data lists from which you need to create a new dictionary.

>>> 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'}

6, Use dictionary derivation to realize key value conversion
You will find that using dictionary derivation is a simpler and more 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'}

7, Use dictionary derivation to 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}

8, Use dictionary derivation to 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

9, Dictionary sort

Starting with Python 3.6, dictionaries are ordered data structures, so if you use Python 3.6 (and later), you will be able to sort the keys of any dictionary by using sorted() and dictionary understanding.

>> 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}

10, Built in function, used with dictionary

Python provides built-in functions that can be useful when you work with collections, such as dictionaries.
1.map() function
Suppose you have a dictionary that contains 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}

2.filter() function
Suppose you want to know the products with unit price lower than 0.40.

>>> 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']

11, Dictionary unpacking operator

This is a concept that many people don't know. Python 3.5 has brought an interesting new feature, so you need to focus on learning.
You can combine two dictionaries into a new dictionary using the dictionary unpacking operator (* *).

>>> 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}

If you try to merge dictionaries that have duplicate or common keys, the values of the rightmost dictionary are supplemented.

Topics: Python