Operation and conversion of data using Python

1. Convert list value to dictionary

In Python, the following code can be used to convert the values ​​​​of a list to the keys of a dictionary:

myList = ["name", "age", "location"]
myDict = {k: None for k in myList}
print(myDict)

output:

{'name': None, 'age': None, 'location': None}

In the above code, we first define a list myList, then, we use dictionary derivation to create a new dictionary myDict, where the key of the dictionary is each element obtained from the list myList, and the corresponding value is set to None.

If you want the values ​​in the list to correspond to different values, just specify the corresponding value in the derivation, for example:

myList = ["name", "age", "location"]
myValues = ["John", 22, "Bei Jing"]
myDict = {myList[i]: myValues[i] for i in range(len(myList))}
print(myDict)

output:

{'name': 'John', 'age': 22, 'location': 'Bei Jing'}

 In the code above, we create a list of keys, values, and then use a loop and dictionary comprehensions to create a dictionary, where each value in the list corresponds to a key and a value in the dictionary.

2. Add new value data to the dictionary key

According to the above code, 2 new pieces of data are added for each key, how to operate

If you want to add multiple values ​​for each key in an existing dictionary, you can store the values ​​in a list, and then use the list as the value corresponding to the key, for example:

myDict = {"name": ["John"], "age": [22], "location": ["Bei Jing"]}
 
# 为 name 增加两个新值
myDict["name"].extend(["Alice", "Bob"])
print(myDict)
 
# 为 age 和 location 增加两个新值
myDict["age"].append(25)
myDict["location"].extend(["Shang Hai", "Guang Zhou"])
print(myDict)

output:

{'name': ['John', 'Alice', 'Bob'], 'age': [22], 'location': ['Bei Jing']}
{'name': ['John', 'Alice', 'Bob'], 'age': [22, 25], 'location': ['Bei Jing', 'Shang Hai', 'Guang Zhou']}

In the above code, we first initialize a list for each key in the dictionary, then we can use the dictionary keys and list methods to add a list consisting of multiple values.

3. Convert new dictionary format

How to change [{'key': 'name', 'value': 'John'}, {'key': 'location', 'value': 'Bei Jing'}] data to {'name': 'John' ', 'location': 'Bei Jing'}

You can use a loop to traverse the dictionaries in the list, and then extract the keys and values ​​of each dictionary to form a new dictionary. details as follows:

# 原始数据
data = [{'key': 'name', 'value': 'John'}, {'key': 'location', 'value': 'Bei Jing'}]
 
# 新的字典
new_dict = {}
for item in data:
    key = item['key']
    value = item['value']
    new_dict[key] = value
 
print(new_dict)

output:

{'name': 'John', 'location': 'Bei Jing'}

First define an empty dictionary new_dict for storing new data. Then use a for loop to iterate through each dictionary in the original data. In the loop, use item['key'] and item['value'] to get the key and value of the current dictionary respectively, and use new_dict[key] = value to store it in a new dictionary, and finally output the new dictionary as Can.

4. Comparison and screening of two sets of data

There are two sets of data, list1['code', 'data.totalPage', 'data.type'] and list2['code', 'description', 'errCode', 'error', 'msg', 'message', 'success', 'btSuccess', 'btCode', 'btMsg', 'header.mss'], if the elements in list1 do not exist in list2, the expected filtering result is ['data.totalPage', 'data.type ']

Filtering can be achieved using list comprehensions and not in statements:

list1 = ['code', 'data.totalPage', 'data.type']
list2 = ['code', 'description', 'errCode', 'error', 'msg', 'message', 'success', 'btSuccess', 'btCode', 'btMsg', 'header.mss']
 
result = [ele for ele in list1 if ele not in list2]
print(result)

output:

['data.totalPage', 'data.type']

Among them, the grammatical format of the list comprehension is: [return value for in conditional statement], which can generate elements that meet the conditions into a new list at one time. The not in statement expresses elements that are not in the list. Therefore, the list comprehension in the above code is to traverse each element ele in list1, and if ele is not in list2, add it to the result list.

5. Merge two independent codes

There are two separate pieces of code, both with for loops

hj = HandleJson(data_dict)
res = hj.find_key_path('request')
print(res)
print(type(res))
# request-循环
for count_i, api_i in enumerate(res):
    # request
    json_request = eval(str(data_dict) + api_i)
    # print("json_request " + str(json_request))
    # name
    json_name = eval(str(data_dict) + api_i.replace("request", "name"))
    print("count_i 第 " + str(count_i + 1) + " 个接口")
    print("json_name " + str(json_name))
 
hj2 = HandleJson(data_dict)
res2 = hj2.find_key_path('response')
print(res2)
print(type(res2))
# response-循环
for count_i, api_i in enumerate(res2):
    # response
    json_response = eval(str(data_dict) + api_i)
    print("json_response " + str(json_response))
    if json_response:
        print("json_response 不为空")
        for count_i_i, api_i_i in enumerate(json_response):
            # print(api_i_i)
            # name
            json_name = eval(str(api_i_i) + str(["name"]))
            print("count_i_i 第 " + str(count_i_i + 1) + " 个接口")
            print("json_name " + str(json_name))

How to combine these two pieces of code

The results of the two loops can be zipped together using the zip() function, and then both lists can be traversed simultaneously in a single for loop. The specific code is as follows:

hj = HandleJson(data_dict)
res = hj.find_key_path('request')
res2 = hj.find_key_path('response')
for count_i, (api_i, api_i2) in enumerate(zip(res, res2)):
    # request-循环的代码内容
    # response-循环的代码内容

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

insert image description here

Software testing interview applet

The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!

The following interview question sections are covered:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too!   

Guess you like

Origin blog.csdn.net/qq_48811377/article/details/132667857