It's worth seeing 13 Python skills that can be used to take off!

Python is one of the widely used programming languages today. It is applied in various fields such as data science, scientific computing, Web development, game development and building desktop graphical interface. Python is popular for its practicality in various fields, productivity compared with other programming languages such as Java, C and C + +, and commands similar to English.

If you are also a Python learning enthusiast, the 13 skills described today are really delicious!

list

The 6 operations related to the list are described below;

1. Merge the two lists into one dictionary

Suppose we have two lists in Python, and we want to combine them into dictionary form. The item of one list is used as the key of the dictionary and the other as the value. This is a very common problem when writing code in Python. However, in order to solve this problem, we need to consider several limitations, such as the size of the two lists, the types of items in the two lists, and whether there are duplicate items, especially the items we will use as keys. We can overcome this problem by using built-in functions such as zip.

keys_list = ['A', 'B', 'C']
values_list = ['blue', 'red', 'bold']

# There are three ways to convert these two lists into dictionaries
# 1. Use Python zip and dict functions
dict_method_1 = dict(zip(keys_list, values_list))

# 2. Use the zip function with dictionary derivation
dict_method_2 = {key:value for key, value in zip(keys_list, values_list)}

# 3. Recycle the zip function
items_tuples = zip(keys_list, values_list) 
dict_method_3 = {} 
for key, value in items_tuples: 
    if key in dict_method_3: 
        pass 
    else: 
        dict_method_3[key] = value

print(dict_method_1)
print(dict_method_2)
print(dict_method_3)

The results are as follows:

2. Merge two or more lists into one list

When we have two or more lists, we want to collect them all into a large list, in which all the first items of the smaller list form the first list in the larger list. For example, if I have four lists [1,2,3], ['a','b','c '], ['h','e','y'], and [4,5,6], we want to create a new list for these four lists; It will be [[1,'a','h',4], [2,'b','e',5], [3,'c','y',6]].

def merge(*args, missing_val = None):
    max_length = max([len(lst) for lst in args])
    outList = []
    for i in range(max_length):
        outList.append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))])
    return outList

merge([1,2,3],['a','b','c'],['h','e','y'],[4,5,6])

The results are as follows:

3. Sort dictionary list

The next set of daily list tasks is sorting tasks. Depending on the data type of the items included in the list, we will sort them in a slightly different way. Let's start by sorting the dictionary list.

dicts_lists = [
  {
    "Name": "James",
    "Age": 20,
  },
  {
     "Name": "May",
     "Age": 14,
  },
  {
    "Name": "Katy",
    "Age": 23,
  }
]

# Method 1
dicts_lists.sort(key=lambda item: item.get("Age"))

# Method 2
from operator import itemgetter
f = itemgetter('Name')
dicts_lists.sort(key=f)

The results are as follows:

4. Sort the string list

We often face lists containing strings that we need to sort by alphabetical order, length, or any other factor we want or need for our application.

Now, I should mention that these are direct ways to sort the string list, but sometimes you may need to implement a sorting algorithm to solve this problem.

my_list = ["blue", "red", "green"]

# Method 1
my_list.sort() 
my_list = sorted(my_list, key=len) 

# Method 2
import locale
from functools import cmp_to_key
my_list = sorted(my_list, key=cmp_to_key(locale.strcoll)) 

The results are as follows:

5. Sort the list according to another list

Sometimes we may want / need to use one list to sort another list. Therefore, we will have a list of numbers (indexes) and a list that I want to sort using these indexes.

a = ['blue', 'green', 'orange', 'purple', 'yellow']
b = [3, 2, 5, 4, 1]

sortedList =  [val for (_, val) in sorted(zip(b, a), key=lambda x: x[0])]
print(sortedList)

The results are as follows:

6. Map list to dictionary

If you give a list and map it to a dictionary. In other words, I want to convert my list into a dictionary with numeric keys. What should I do?

mylist = ['blue', 'orange', 'green']
#Map the list into a dict using the map, zip and dict functions
mapped_dict = dict(zip(itr, map(fn, itr)))

Dictionaries

The 2 dictionary related operations are described below;

7. Merge two or more dictionaries

Suppose we have two or more dictionaries and we want to merge them all into one dictionary with unique keys.

from collections import defaultdict

def merge_dicts(*dicts):
    mdict = defaultdict(list)
    for dict in dicts:
    for key in dict:
        res[key].append(d[key])
    return dict(mdict)

8. Reverse dictionary

A very common dictionary task is if we have a dictionary and want to reverse its keys and values. Therefore, the key becomes the value and the value becomes the key. When we do this, we need to make sure that I don't have duplicate keys, that values can be repeated, but keys can't, and that all new keys are hashable.

my_dict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
# Method 1
my_inverted_dict_1 = dict(map(reversed, my_dict.items()))

# Method 2
from collections import defaultdict
my_inverted_dict_2 = defaultdict(list)
{my_inverted_dict_2[v].append(k) for k, v in my_dict.items()}

print(my_inverted_dict_1)
print(my_inverted_dict_2)

The results are as follows:

character string

Three operations related to strings are described as follows:;

9. Use f string

Formatting strings can be the first task you need to do almost every day. There are many ways to format strings in Python; My favorite is to use the f string.

str_val = 'books'
num_val = 15
print(f'{num_val} {str_val}') 
print(f'{num_val % 2 = }') 
print(f'{str_val!r}') 

price_val = 5.18362
print(f'{price_val:.2f}') 

from datetime import datetime;
date_val = datetime.utcnow()
print(f'{date_val=:%Y-%m-%d}') 

The results are as follows:

10. Check substring

A very common task that I have to perform many times before is to check whether the string is in the string list.

addresses = ["123 Elm Street", "531 Oak Street", "678 Maple Street"]
street = "Elm Street"

# Method 1
for address in addresses:
    if address.find(street) >= 0:
        print(address)

# Method 2
for address in addresses:
    if street in address:
        print(address)

The results are as follows:

11. Get the size of the string in bytes

Sometimes, especially when building memory critical applications, we need to know how much memory our strings use. Fortunately, this can be done quickly with one line of code.

str1 = "hello"
str2 = "😀"

def str_size(s):
    return len(s.encode('utf-8'))

print(str_size(str1))
print(str_size(str2))

The results are as follows:

Input / output operation

Two operations related to input / output operations are described below;

12. Check whether the file exists

In data science and many other applications, we often need to read data from or write data to files. But to do this, we need to check whether the file exists. Therefore, our code will not terminate due to errors.

# Method 1
import os 
exists = os.path.isfile('/path/to/file')

# Method 2
from pathlib import Path
config = Path('/path/to/file') 
if config.is_file(): 
    pass

13. Parse spreadsheet

Another very common file interaction is parsing data from spreadsheets. Fortunately, we have a CSV module to help us perform this task effectively.

import csv
csv_mapping_list = []
with open("/path/to/data.csv") as my_data:
    csv_reader = csv.reader(my_data, delimiter=",")
    line_count = 0
    for line in csv_reader:
        if line_count == 0:
            header = line
        else:
            row_dict = {key: value for key, value in zip(header, line)}
            csv_mapping_list.append(row_dict)
        line_count += 1

end of document

Your favorite collection is my greatest encouragement!
Welcome to follow me, share Python dry goods and exchange Python technology.
If you have any opinions on the article or any technical problems, please leave a message in the comment area for discussion!

Keywords: Python Back-end

Added by edspace on Wed, 15 Dec 2021 22:10:59 +0200