d1 = {"a1": 1,"a2": 2,"a3": 3,"a4": 4,"a5": 5,}
d2 = {"a4": 90,"a6": 5,"a1": 2,"a9": 8,"a8": 9,}
# 1. 获取d1和d2key的交集,并以d2的值为主生成dict
# 2. 去掉d1和d2中key重复以及value重复的值,合并成一个dict
#!/usr/bin/env python
d1 = {"a1": 1,"a2": 2,"a3": 3,"a4": 4,"a5": 5}
d2 = {"a4": 90,"a6": 5,"a1": 2,"a9": 8,"a8": 9}
dict = {}
set_key = set(d1.keys()) & set(d2.keys())
new_list = list(set_key)
for i in new_list:
new_value = d2.__getitem__(i)
dict_new = {i : new_value}
dict.update(dict_new)
print dict
#!/usr/bin/env python
d1 = {"a1": 1,"a2": 2,"a3": 3,"a4": 4,"a5": 5}
d2 = {"a4": 90,"a6": 5,"a1": 2,"a9": 8,"a8": 9}
set_key = set(d1.keys()) & set(d2.keys())
new_list = list(set_key)
for i in new_list:
d1.pop(i)
d2.pop(i)
d1.update(d2)
dict = d1
print dict
时间: 2024-10-19 18:36:59