1、从输入的字典中获取给定key的值,
实现函数:get_key_value(source_dict, key, index=0),source_dict指给定的字典,key指需要获取的key字段,index指的是需要获取相同key的第几个值,从0开始,默认是0。
调用函数:get_key_value(a, ‘ffa’, 1),返回值应该是:['423', 'd23e']
a = {
'a': '323',
'fads': '3edfsd',
'fad': [
{
'wew': '23',
'ffa': ['122', '333', '133'],
'ewe': '23'
},
{
'wew': '2333',
'ffa': ['423', 'd23e'],
'ewe': '009'
}
]
}
'''
先判断key在不在最外层字典的keys中,若在直接取值,\
若不在,说明在value对应的嵌套字典中(当然也有可能不存在,但是不影响,只是取不到值而已),\
于是遍历最外层字典的value,进一步判断value,若是字典,接着循环,\
若是列表,遍历取值,再判断,这样可以定义两个函数相互调用就行了
'''
a = {
'a': '323',
'fads': '3edfsd',
'fad': [
{
'wew': '23',
'ffa': ['122', '333', '133'],
'ewe': '23'
},
{
'wew': '2333',
'ffa': ['423', 'd23e'],
'ewe': '009'
}
]
}
def get_target_value(dic, key, tmp_list):
if not isinstance(dic, dict) or not isinstance(tmp_list, list): # 对传入数据进行格式校验
return '格式错'
if key in dic.keys():
tmp_list.append(dic[key]) # 传入数据存在则存入tmp_list
else:
for value in dic.values(): # 传入数据不符合则对其value值进行遍历
if isinstance(value, dict):
get_target_value(value, key, tmp_list) # 传入数据的value值是字典,则直接调用自身
elif isinstance(value, (list, tuple)):
judge_value(value, key, tmp_list) # 传入数据的value值是列表或者元组,则调用judge_value
return tmp_list
def judge_value(val, key, tmp_list):
for val_ in val:
if isinstance(val_, dict):
get_target_value(val_, key, tmp_list) # 传入数据的value值是字典,则调用get_target_value
elif isinstance(val_, (list, tuple)):
judge_value(val_, key, tmp_list) # 传入数据的value值是列表或者元组,则调用自身
def get_result(source_dict, key, index):
test_list = []
target_value = get_target_value(source_dict, key, test_list)
if test_list and index in range(len(target_value)):
return test_list[index]
else:
print("相同key对应value最多有{}个,输入超出范围,默认返回所有".format(len(target_value)))
return test_list
test_dict = a
test_key = 'ffa'
index = 1
result = get_result(test_dict, test_key, index)
print(result)
参考链接: https://www.cnblogs.com/Detector/p/8085460.html
2、从文件中获取指定字符所在行数据。实现函数:check_string(file_path, key_word),file_path代表文件所在路径,key_word代码搜索的关键字,返回符合条件的列表
现有文件:a.log,文件内容如下:
update starting
Mysql update starting....
Mysql update complete
AuthServer update starting....
AuthServer update complate
NetWorkServer update starting...
NetWorkServer update complate
GDPSServer update starting...
GDPSServer update complate
[update result] successful...
现在进行如下调用:check_string(‘D:\a.log’,‘update result’),则返回:[‘[update result] successful…’]。如果进行如下调用:check_string(‘D:\a.log’,‘complate’),则返回:[‘Mysql update complete’, ‘AuthServer update complate’, ‘NetWorkServer update complate’, ‘GDPSServer update complate’]
def check_string(file_path, key_word):
file_read = open(file_path, 'r')
return_list = []
f = file_read.readlines()
for line in f:
if key_word in line:
return_list.append(line.strip('\n'))
return return_list
find_word = 'update result'
find_path = 'G:\Python\homework\\a.log'
check_string = check_string(find_path, find_word)
if not check_string:
print('关键字检索结果为空,请重新输入关键字')
else:
print('返回结果为:', check_string)