Created
July 11, 2013 09:04
-
-
Save senko/5973841 to your computer and use it in GitHub Desktop.
updated - create and return a new Python dictionary by merging multiple dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Written in 2013. by Senko Rasic <[email protected]> | |
# 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