关于python:检查具有相似键但值不同的两个词典

check two dictionaries that have similar keys but different values

我有两本词典。dict1和dict2。dict 2的长度总是相同的,但dict1的长度不同。两部词典如下:

1
2
3
dict2 = {"name":"martin","sex":"male","age":"97","address":"blablabla"}

dict1 = {"name":"falak","sex":"female"}

我想创建一个基于dict1和dict2的第三个字典。dict3将具有dict2的所有值。但所有那些在dict1中存在的键都将被替换。下面是结果dict3

1
dict3 = {"name":"falak","sex":"female","age":"97","address":"blablabla"}

我可以用多个if语句来实现它,但是我希望有一种更聪明的方法。有人能指导我吗?


您是否尝试过:

1
dict3 = dict(dict2, **dict1)

或:

1
2
dict3 = dict2.copy()
dict3.update(dict1)


1
2
3
import copy
dict3 = copy.copy(dict2)
dict3.update(dict1)


首先,添加d1中具有d2中不存在的键的项。来自d1的所有其他键都在d2中。

然后,添加d2中的所有键,如果d1中没有这样的键,则从d2添加值;如果d1中存在键,则从d1添加值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
dict2 = {"name":"martin","sex":"male","age":"97","address":"blablabla"}
dict1 = {"name":"falak","sex":"female"}

dic = dict()

for key, val in dict1.items():
  if key not in dict2.keys():
    dic[key] = val

for key, val in dict2.items():
  if key not in dict1.keys():
    dic[key] = val
  else:
    dic[key] = dict1[key]


从python文档中:

update([other])

  • Update the dictionary with the key/value pairs from other, overwriting existing keys.
  • Returns None.
  • update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
  • Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.

所以:

1
dict1.update(dict2)