Skip to content

Instantly share code, notes, and snippets.

@lordlycastle
Last active January 9, 2019 13:10
Show Gist options
  • Save lordlycastle/431a48c71b9e7cd4b8224364d634c166 to your computer and use it in GitHub Desktop.
Save lordlycastle/431a48c71b9e7cd4b8224364d634c166 to your computer and use it in GitHub Desktop.
function to combine dictionaries and list keys that are overwritten.
a = {1: -1, 2: -2}
b = {2: 2, 3: -3}
c = {3: 3, 4: -4}
d = {3: 3j, 5: -5}
def combine_dicts(*args):
"""Combines multiple dictionaries in one. Overwrites the value of keys if they occur in multiple dicts.
Value is taken from the """
x = args
overwritten_keys = []
for i in range(1, len(x)):
for key in x[i].keys():
found_match = False
for j in range(len(x) - 1, i - 1, -1):
if key in x[j]:
overwritten_keys.append(key)
found_match = True
break
if len(overwritten_keys) > 0:
print('Following dict key-values will be overwritten by the last dict containing the key: {}'.format(overwritten_keys))
return {k: v for i in x for k, v in i.items()}
z = combine_dicts(a, b, c, d)
print(z)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment