将两个字典合并为一个,以dict2中的元素为准

2024-10-03 13:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

def combine_guests(guests1, guests2):
  # Combine both dictionaries into one, with each key listed 
  # only once, and the value from guests1 taking precedence

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}

print(combine_guests(Rorys_guests, Taylors_guests))

想要这个输出吗

{"Adam": [2, 1], "Branda": 3, "David": [1, 4] ...}

对于来自guests1的值,即Rorys_guests dict将优先。例如,对于Adam,键值为[2,1]


Tags: defonerobertdavidcombineadambothinto
3条回答

这可能会有帮助。这将优先于Rorys_guests,并且不包括来自Taylors_guests的值(如果两者都具有该值)

Taylors_guests.update(Rorys_guests)
return Rorys_guests

Python 3.5或更高版本

z = {**Rorys_guests , **Taylors_guests }
def combine_guests(guests1, guests2):
    #Update function will add new values and update existing values in the dictionary
    guests2.update(guests1)
    return guests2

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}

print(combine_guests(Rorys_guests, Taylors_guests))

相关问题 更多 >