The way to Python’s advancement (2) dict’s advanced classic

Time:2020-2-3

happy new year

Hello everyone, today is the second day of the lunar new year. I have no atmosphere for Chinese New Year in foreign countries. I can only write articles and make some contributions to the community. I wish you a happy New Year! In the last issue, I sorted out some advanced uses of list for you. Today, let’s look at the related skills of dictionary dict. I use the dictionary very frequently in my programming. Actually, for the demand of not very large data storage, dictionary is a good choice, much faster than list. I talked about some basic methods of dict in the basic chapter, if I haven’t seen any friends Friends can click the link Python basic start (8) dictionary practical skills, OK, gossip less, now let’s take a look at today’s advanced skills~

Dictionary advanced method summary

Create dictionary

Here are some of the most common ways, for example:

First = {} create an empty dictionary
Second = dict() ා create an empty dictionary

keys = ['Name','Age','Job','Salary']
values = ['White',50,'cook',10000]
Third = dict (ZIP (keys, values)) (zip creation)

Font = dict (name ='white ', age = 50, job ='cook', salary = 10000) ා equal sign creation

fifth = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
         2: {'name':'marie ',' age ':'22', 'sex':'female '}} 񖓿 create a nested dictionary

print(first)
print(second)
print(third)
print(fouth)
print(fifth[1])


Out: {}
     {}
     {'Name': 'White', 'Age': 50, 'Job': 'cook', 'Salary': 10000}
     {'Name': 'White', 'Age': 50, 'Job': 'cook', 'Salary': 10000}
     {'name': 'John', 'age': '27', 'sex': 'Male'}

Here, we can directly use {} or dict () to create an empty dictionary, or directly assign a value to the dictionary in the form of key: value. Zip and equal sign can also be assigned directly. If we need multiple layers of nested, we can also implement it easily. There are so many things about creation

Dictionary ranking

For dictionary sorting, we have two options: first, sorting according to the key value of the dictionary, and second, sorting according to the value value value. Let’s see one by one. First, let’s create a new dictionary for testing:

final_result= dict(Math=80,Chinese=78,English=96,Science=60,Art=75)
print(final_result.items())

Out: dict_items([('Math', 80), ('Chinese', 78), ('English', 96), ('Science', 60), ('Art', 75)])
Sort by key value

Here, we create a dictionary final “result. The key value is the name of the subject, and the value value is the score. First, we sort by the key value. First, let’s ascending by the key value. There are many options, such as sorted, operator, Lamba:

Print (sorted (final result. Items()) (in ascending order according to the value of key)
Out:[('Art', 75), ('Chinese', 78), ('English', 96), ('Math', 80), ('Science', 60)]
import operator
print(sorted(final_result.items(),key=operator.itemgetter(0)))
Out:[('Art', 75), ('Chinese', 78), ('English', 96), ('Math', 80), ('Science', 60)]
print(sorted(final_result.items(),key=lambda x:x[0]))
Out:[('Art', 75), ('Chinese', 78), ('English', 96), ('Math', 80), ('Science', 60)]

According to the descending key value, just add a reverse = true, because the sorted function defaults to reverse = false. See the following results:

Print (sorted (final result. Items(), reverse = true)) ා descending by the value of key
Out:[('Science', 60), ('Math', 80), ('English', 96), ('Chinese', 78), ('Art', 75)]
import operator
print(sorted(final_result.items(),key=operator.itemgetter(0),reverse=True))
Out:[('Science', 60), ('Math', 80), ('English', 96), ('Chinese', 78), ('Art', 75)]

print(sorted(final_result.items(),key=lambda x:x[0],reverse=True))
Out:[('Science', 60), ('Math', 80), ('English', 96), ('Chinese', 78), ('Art', 75)]

There are so many functions about Lamba that can be summed up. I will take one issue specifically later. It’s a magic weapon with filter reduce. When I use it more and more, I finally feel a little bit of Python. Ha ha

Sort by value

In fact, you can see the sorting by key and guess how to sort by value. Let’s look at ascending order first:

Print (sorted (final result. Items(), key = lambda x: x [1])) (ascending by value)
Out:[('Science', 60), ('Art', 75), ('Chinese', 78), ('Math', 80), ('English', 96)]
import operator
print(sorted(final_result.items(),key=operator.itemgetter(1)))

Out:[('Science', 60), ('Art', 75), ('Chinese', 78), ('Math', 80), ('English', 96)]

The descending order is the same, except that reverse = true is added. Here are some examples:

print(sorted(final_result.items(),key=lambda v:v[1],reverse=True))
Out:[('English', 96), ('Math', 80), ('Chinese', 78), ('Art', 75), ('Science', 60)]

Dictionary merge

You can use * * directly in Python 3.5 or above. It’s a common trick. I’m sorry for the 2.7 users. The technology has always been said to be new and old. Let’s look at a little Chestnut:

def Merge(dict1, dict2):
    res = {**dict1, **dict2}
    return res

dict1 = {'a': 10, 'b': 8,'c':2}
dict2 = {'d': 6, 'c': 4}
dict3 = Merge(dict1, dict2)
print(dict3)

Out:{'a': 10, 'b': 8, 'c': 4, 'd': 6}

The order here is very important. You must see who covers whom. If we exchange the order, it will be like this:

def Merge(dict1, dict2):
    Res = {* * dict2, * * dict1} swapped order
    return res

dict1 = {'a': 10, 'b': 8,'c':2}
dict2 = {'d': 6, 'c': 4}
dict3 = Merge(dict1, dict2)
print(dict3)
Out:{'d': 6, 'c': 2, 'a': 10, 'b': 8}

Don’t worry about Python 2 friends. There is a natural solution. That is to use the update function, which is also very convenient

dict1 = {'a': 10, 'b': 8,'c':2}
dict2 = {'d': 6, 'c': 4}

dict2.update(dict1)
print(dict2)

Out:{'d': 6, 'c': 2, 'a': 10, 'b': 8}

Beautify output dict with JSON. Dumps()

If we encounter dict in the following situations, the normal print output will look like this:

my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
print(my_mapping)
Out:{'a': 23, 'b': 42, 'c': 12648430}

But if we can refer to the dumps method in the JSON library, we will get much better results:

import json
print(json.dumps(my_mapping, indent=4, sort_keys=True))
Out:{
    "a": 23,
    "b": 42,
    "c": 12648430
    }

Unpacking dictionary parameters

There are many convenient and magical methods in Python, such as the following one, which can realize the unpacking Dictionary:

def unpack(k1,k2,k3):
    print(k1,k2,k3)

my_dict = {'k1':'value1','k2':'value2','k3':'value3'}
unpack(**my_dict)

Out: value1 value2 value3

By the way, I’ll talk about args and kwargs in a later issue. Please wait!

Dictionary derivation

I wrote this in a tangled way, because I consulted my supervisor and he recommended that I try not to use it. I don’t know the reason. I don’t know if there is a great God who can come out to solve it. The specific usage is the same as the derivation of list, and the code is as follows:

import json
first = {x:'A'+str(x) for x in range(8)}
Print (JSON. Dumps (first, indent = 4, sort ﹐ keys = true)) ﹐ in this case, it's better to use JSON output
 
Out:{             
    "0": "A0",
    "1": "A1",
    "2": "A2",
    "3": "A3",
    "4": "A4",
    "5": "A5",
    "6": "A6",
    "7": "A7"
     }

Or you can use it like this:

second={v:k for k,v in first.items()}
print(json.dumps(second,indent=4))
Out:{
    "A0": 0,
    "A1": 1,
    "A2": 2,
    "A3": 3,
    "A4": 4,
    "A5": 5,
    "A6": 6,
    "A7": 7
     }

As for other messy uses, you can think about it yourself

summary

Today, I have systematically reviewed several points for you:

  • Different ways to create a dictionary
  • Dictionary ranking
  • Dictionary merging
  • Dictionary unpacking
  • JSON optimized output
  • Dictionary derivation

I hope I can help you. In the future, if I want to have any interesting methods and skills, I will add them. If you are interested in dict
Interested in other skills, you can pay attention to my WeChat public Python minimalist tutorial. I will record and share the most efficient and concise tips.

The way to Python's advancement (2) dict's advanced classic

Recommended Today

High quality app architecture design and thinking!

Recently, I have been working on a small number of apps with small functions and complex businesses. In the past, I found that I never considered some architectural problems when I was working on an app. I just wrote code according to my previous habits and ignored the design of the app. This sharing mainly […]