python dict 常用操作

定义两个dict:

dict_a = {"A": 123, "B": 456}
dict_b = {"C": 11, "A": 234}

1. 按key取交集

dict_c = {k: v for k, v in dict_a.items() if k in dict_b.keys()}
print(dict_c)

结果:
{‘A‘: 123}

2 按key取差集

dict_e = {k: v for k, v in dict_a.items() if k not in dict_b.keys()}
print(dict_e)

结果:
{‘B‘: 456}

3.按key取并集

dict_d = {**dict_a, **dict_b}
print(dict_d)

结果(注意"A"的值):
{‘A‘: 234, ‘B‘: 456, ‘C‘: 11}

相关推荐