簡體   English   中英

如何在Python中僅將一個字典中的新密鑰對附加到另一個字典?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM