Skip to content

Instantly share code, notes, and snippets.

@flash42
Last active May 29, 2020 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flash42/5d7013452e4c6fc4221ffab82f3e6668 to your computer and use it in GitHub Desktop.
Save flash42/5d7013452e4c6fc4221ffab82f3e6668 to your computer and use it in GitHub Desktop.
[ProgBasics] merge_dict
# https://github.com/morcsanyitamas/pythonic-dictionaries
dict_one = {'a': 1, 'b': 2, 'c': 3}
dict_two = {'d': 1, 'e': 2, 'f': 3, 'a': 99}
def sort_dict(d):
from collections import OrderedDict
return OrderedDict(sorted(d.items()))
def merge_dict(a, b):
return {key:a.get(key, 0) + b.get(key, 0) for key in set(list(a.keys()) + list(b.keys()))}
print(sort_dict(merge_dict(dict_one, dict_two)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment