获取字典中的objkey对应的值,适用于字典嵌套
# dict:字典
# objkey:目标key
# default:找不到时返回的默认值
def dict_get(dict, objkey, default):
for k, v in dict.items():
if k == objkey:
return v
else:
if type(v) is types.DictType: # 如果字典的值同为字典,进行递归调用
ret = dict_get(v, objkey, default)
if ret is not default:
return ret
return default # 如果未找到key对应的值,返回default
# 示例
dicttest={"result":{"code":"110002","msg":"设备设备序列号或验证码错误"},'a':1}
ret=dict_get(dicttest, 'msg', None)
print(ret)
去除重复的字典
# items:仅包含字典的可迭代对象(tuple/list)
# key:获取字典值的规则
def dedupe(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
# 示例
a = {'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}
print list(dedupe(a, key=lambda d: (d['x'],d['y'])))