From: Eli Bendersky Date: Mon, 15 Jan 2018 13:50:13 +0000 (-0800) Subject: Adding a dict-merging utility X-Git-Tag: v0.25~19 X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=18c99a9ee53b2634fd150b00c0b3f007dea0a7d4;p=pyelftools.git Adding a dict-merging utility --- diff --git a/elftools/common/utils.py b/elftools/common/utils.py index d8acefa..4e80e18 100644 --- a/elftools/common/utils.py +++ b/elftools/common/utils.py @@ -12,6 +12,14 @@ from .py3compat import int2byte from ..construct import ConstructError +def merge_dicts(*dicts): + "Given any number of dicts, merges them into a new one.""" + result = {} + for d in dicts: + result.update(d) + return result + + def bytelist2string(bytelist): """ Convert a list of byte values (e.g. [0x10 0x20 0x00]) to a bytes object (e.g. b'\x10\x20\x00'). diff --git a/test/test_utils.py b/test/test_utils.py index 86b1da1..23669e7 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -8,7 +8,7 @@ import unittest from random import randint from elftools.common.py3compat import int2byte, BytesIO -from elftools.common.utils import (parse_cstring_from_stream, +from elftools.common.utils import (parse_cstring_from_stream, merge_dicts, preserve_stream_pos) @@ -54,5 +54,15 @@ class Test_preserve_stream_pos(unittest.TestCase): self.assertEqual(sio.tell(), 5) +class Test_merge_dicts(unittest.TestCase): + def test_basic(self): + md = merge_dicts({10: 20, 20: 30}, {30: 40, 50: 60}) + self.assertEqual(md, {10: 20, 20: 30, 30: 40, 50: 60}) + + def test_keys_resolve(self): + md = merge_dicts({10: 20, 20: 30}, {20: 40, 50: 60}) + self.assertEqual(md, {10: 20, 20: 40, 50: 60}) + + if __name__ == '__main__': unittest.main()