python的setdefault()方法
阿新 • • 發佈:2018-11-21
描述
Python 字典 setdefault() 函式和get() 方法類似, 如果鍵不存在於字典中,將會新增鍵並將值設為預設值。
語法
setdefault()方法語法:
dict.setdefault(key, default=None)
引數
key -- 查詢的鍵值。
default -- 鍵不存在時,設定的預設鍵值。
返回值
如果字典中包含有給定鍵,則返回該鍵對應的值,否則返回為該鍵設定的值。
現有一需求,再不改變原來結構的基礎上,新增欄位
比如
根據圖一中具有與圖二相同的CacheParameterGroupFamily,
將圖一中CacheParameterGroupName新增到對應的圖二中
結果呈現
程式碼:
#圖一取出資料 即列表 cache_parameter_groups = first_one['CacheParameterGroupName'] #定義一個字典 group_family_map = dict() #迴圈圖一的列表 for cpg in cache_parameter_groups: # 利用python的setdefault(key, default=None)方法 構造一個{key:[]} group_family_map.setdefault(cpg['CacheParameterGroupFamily'], []) #將CacheParameterGroupName 新增進去 group_family_map[cpg['CacheParameterGroupFamily']].append(cpg['CacheParameterGroupName']) #圖二取出資料 即列表 res = two['CacheEngineVersions'] for r in res: r['CacheParameterGroups'] = group_family_map.get(r['CacheParameterGroupFamily']) return res