python 字典取(不存在)值


背景以及造成原因:

  在數據庫存儲的時候,常常會遇到不確定參數的情況即可變參數,在創建的時候使用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)

效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM