From 18c99a9ee53b2634fd150b00c0b3f007dea0a7d4 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 15 Jan 2018 05:50:13 -0800 Subject: [PATCH] Adding a dict-merging utility --- elftools/common/utils.py | 8 ++++++++ test/test_utils.py | 12 +++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) 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() -- 2.30.2