背景以及造成原因:
在数据库存储的时候,常常会遇到不确定参数的情况即可变参数,在创建的时候使用JSON格式字段,将不确定key的数据放在该字段里面,后面使用该字段的时候就容易出现key不存在的情况
情况如下图:

解决方式:
1、用存在于字典的key于所查的做对比,一致就返回值,其他的就另作处理
代码块:
dict_data = {'manager': '区域负责人',
'pic_conf': {'pic_name_1': ['SW01']},
'pic_path': '',
'technique': ['技术', '技术2'],
'fresh_time': 10,
'switch_time': 5,
'machine_code': ['SW01'],
'technique_title': '技术',
'workcenter_code': 'GF_CNC_SW',
'production_target': [{'target_name': '2h_SW01', 'machine_code': 'SW01'}]}
val = ''
for key, value in dict_data.items():
if key == 'name':
val = value
print(val or None)
效果图:

2、使用 defaultdict 模块格式化
defaultdict接受一个工厂函数作为参数,这个factory_function可以是list、set、str等等,作用是当key不存在时,返回的是工厂函数的默认值,比如list对应[ ],str对应的是空字符串,set对应set( ),int对应0
效果图:

(1、用函数将原数据数据放进defaultdict里面
代码块:
dict_data = {'manager': '区域负责人',
'pic_conf': {'pic_name_1': ['SW01']},
'pic_path': '',
'technique': ['技术', '技术2'],
'fresh_time': 10,
'switch_time': 5,
'machine_code': ['SW01'],
'technique_title': '技术',
'workcenter_code': 'GF_CNC_SW',
'production_target': [{'target_name': '2h_SW01', 'machine_code': 'SW01'}]}
def build_dict(old_dict: dict):
new_dict = defaultdict(dict)
for key, value in old_dict.items():
new_dict[key] = value
return new_dict
data = build_dict(dict_data)
print(data['name'] or None)
效果图:

(2、使用defaultdict自带的方式写入
代码块:
from collections import defaultdict dict_data = {'manager': '区域负责人', 'pic_conf': {'pic_name_1': ['SW01']}, 'pic_path': '', 'technique': ['技术', '技术2'], 'fresh_time': 10, 'switch_time': 5, 'machine_code': ['SW01'], 'technique_title': '技术', 'workcenter_code': 'GF_CNC_SW', 'production_target': [{'target_name': '2h_SW01', 'machine_code': 'SW01'}]} ddd = defaultdict(dict, **dict_data) print(ddd['name'] or None)
效果图:

