Files
30-seconds-of-code/snippets/merge_dictionaries.md
2022-03-22 12:32:56 +02:00

602 B

title, tags, expertise, author, firstSeen, lastUpdated
title tags expertise author firstSeen lastUpdated
Merge dictionaries dictionary intermediate maciv 2020-04-16T19:28:35+03:00 2020-11-02T19:28:27+02:00

Merges two or more dictionaries.

  • Create a new dict and loop over dicts, using dictionary.update() to add the key-value pairs from each one to the result.
def merge_dictionaries(*dicts):
  res = dict()
  for d in dicts:
    res.update(d)
  return res
ages_one = {
  'Peter': 10,
  'Isabel': 11,
}
ages_two = {
  'Anna': 9
}
merge_dictionaries(ages_one, ages_two)
# { 'Peter': 10, 'Isabel': 11, 'Anna': 9 }