Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
updated - create and return a new Python dictionary by merging multiple dictionaries
#!/usr/bin/env python
#
# Written in 2013. by Senko Rasic <senko.rasic@dobarkod.hr>
# This code is Public Domain. You may use it as you like.
__all__ = ['updated']
def updated(dct, *others):
"""Create and return a new dictionary by merging multiple dictionaries.
Creates a copy of dictionary `dct` and updates it with items from the
other dictionaries in the order they were specified. If items with the
same key appear in multiple dictionaries, the value used in the last
appearance is used for the resulting dict.
The function doesn't modify any of the arguments in any way.
Returns the newly created dictionary.
"""
dct = dct.copy()
for other in others:
dct.update(other)
return dct
if __name__ == '__main__':
from unittest import TestCase, main
class UpdatedTests(TestCase):
def test_updated_single_argument_copies_dict(self):
a = {'foo': 1}
b = updated(a)
a = {}
self.assertEqual(b, {'foo': 1})
def test_updated_multiple_arguments_merges_items(self):
a = updated({'foo': 1}, {'bar': 2}, {'baz': 3})
self.assertEqual(a, {'foo': 1, 'bar': 2, 'baz': 3})
def test_updated_multiple_key_values_use_last_value(self):
a = updated({'foo': 1}, {'foo': 2}, {'foo': 3})
self.assertEqual(a, {'foo': 3})
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment