在Python/ target=_blank class=infotextkey>Python中,将列表的值转换为字典的键可以使用以下代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试
myList = ["name", "age", "location"]
myDict = {k: None for k in myList}
print(myDict)
{'name': None, 'age': None, 'location': None}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试
myList = ["name", "age", "location"]
myValues = ["John", 22, "Bei Jing"]
myDict = {myList[i]: myValues[i] for i in range(len(myList))}
print(myDict)
{'name': 'John', 'age': 22, 'location': 'Bei Jing'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试
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)
{'name': ['John', 'Alice', 'Bob'], 'age': [22], 'location': ['Bei Jing']}
{'name': ['John', 'Alice', 'Bob'], 'age': [22, 25], 'location': ['Bei Jing', 'Shang Hai', 'Guang Zhou']}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试
# 原始数据
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)
{'name': 'John', 'location': 'Bei Jing'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试
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)
['data.totalPage', 'data.type']
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))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试
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-循环的代码内容