Как объединить два словаря в python?

Пользователь

от sylvester , в категории: Python , 2 года назад

Как объединить два словаря в python?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

2 ответа

Пользователь

от NicolasSsh , 2 года назад

@sylvester  Вы можете использовать метод распаковки словарей для их объединения.


1
2
3
4
5
6
7
8
first_array = {"Philosophers stone" : 15, "Chamber of Secrets" : 20, "Prisoner of Azkaban" : 10, "Goblet of Fire" : 14}
second_array = {"Order of the Phoenix" : 20, "Half-Blood Prince" : 16, "Deathly Hallows" : 24}

total_chapters = {**first_array, **second_array}

print(total_chapters)

# Вывод : {'Philosophers stone': 15, 'Chamber of Secrets': 20, 'Prisoner of Azkaban': 10, 'Goblet of Fire': 14, 'Order of the Phoenix': 20, 'Half-Blood Prince': 16, 'Deathly Hallows': 24}

Пользователь

от autumn_parker , год назад

@sylvester 

Вы можете использовать метод update() у словаря, чтобы объединить два словаря.

1
2
3
4
5
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

dict1.update(dict2)
print(dict1)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}


Вы также можете использовать генератор выражений, чтобы создать новый словарь, объединяя два словаря:

1
2
3
4
5
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

combined_dict = {**dict1, **dict2}
print(combined_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}