[英]How to append only new key pair from one dictionary to another in Python?
我有这两个字典:
Rorys_guests = {"Adam": 2, "Brenda": 3, "David": 1, "Jose": 3, "Charlotte": 2, "Terry": 1, "Robert": 4}
Taylors_guests = {"David": 4, "Nancy": 1, "Robert": 2, "Adam": 1, "Samantha": 3, "Chris": 5}
我想检查 Taylors_guests 中的钥匙(只有钥匙)是否已经在 Rorys_guests 中。 如果没有,我想将 Taylors 的键值对附加到 Rorys。
注意:两个字典中的某些键是相同的。 我不想覆盖 Rorys_guests 中的值。 我只想从 Taylors 字典中附加尚未在 Rorys 字典中的键和值。
for i in Taylors_guests:
print(i)
if i in Rorys_guests:
print("yes")
else:
Rorys_guests = Rorys_guests.get(i)
print(Rorys_guests)
我是一个 python 菜鸟,但仍然浏览了许多不同的网站,但找不到解决方案。
先感谢您!
Rorys_guests = {**Rorys_guests, **Taylors_guests}
# {'Adam': 2, 'Brenda': 3, 'David': 1, 'Jose': 3, 'Charlotte': 2, 'Terry': 1, 'Robert': 4, 'Nancy': 1, 'Samantha': 3, 'Chris': 5}
我相信你非常接近,但我认为应该这样做:
Rorys_guests = {"Adam": 2, "Brenda": 3, "David": 1, "Jose": 3, "Charlotte": 2,
"Terry": 1, "Robert": 4}
Taylors_guests = {"David": 4, "Nancy": 1, "Robert": 2, "Adam": 1, "Samantha":
3, "Chris": 5}
for k,v in Taylors_guests.items():
if k not in Rorys_guests.keys():
Rorys_guests[k] = Taylors_guests[k]
print(Rorys_guests)
输出:
{'Adam': 2, 'Brenda': 3, 'David': 1, 'Jose': 3, 'Charlotte': 2, 'Terry': 1, 'Robert': 4, 'Nancy': 1, 'Samantha': 3, 'Chris': 5}
你可以试试这个:
Rorys_guests = {"Adam": 2, "Brenda": 3, "David": 1, "Jose": 3, "Charlotte": 2, "Terry": 1, "Robert": 4}
Taylors_guests = {"David": 4, "Nancy": 1, "Robert": 2, "Adam": 1, "Samantha": 3, "Chris": 5}
for key, value in Taylors_guests.items():
if key not in Rorys_guests:
Rorys_guests[key] = value
print(Rorys_guests)
您可以像这样在一行中完成:
Rorys_guests = {"Adam": 2, "Brenda": 3, "David": 1, "Jose": 3, "Charlotte": 2, "Terry": 1, "Robert": 4}
Taylors_guests = {"David": 4, "Nancy": 1, "Robert": 2, "Adam": 1, "Samantha": 3, "Chris": 5}
Rorys_guests.update({k:v for k,v in Taylors_guests.items() if k not in Rorys_guests.keys()})
print(Rorys_guests)
>>> {'Adam': 2, 'Brenda': 3, 'David': 1, 'Jose': 3, 'Charlotte': 2, 'Terry': 1, 'Robert': 4, 'Nancy': 1, 'Samantha': 3, 'Chris': 5}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.