描述
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