Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:58:22

0001 #!/usr/bin/env python
0002 #
0003 # Licensed under the Apache License, Version 2.0 (the "License");
0004 # You may not use this file except in compliance with the License.
0005 # You may obtain a copy of the License at
0006 # http://www.apache.org/licenses/LICENSE-2.0OA
0007 #
0008 # Authors:
0009 # - Wen Guan, <wen.guan@cern.ch>, 2023
0010 
0011 
0012 def merge_dict(dict1, dict2):
0013     print("merge: %s, %s" % (dict1, dict2))
0014     # keys = list(dict1.keys()) + list(dict2.keys())
0015     keys = list(dict1.keys())
0016     for key in list(dict2.keys()):
0017         if key not in keys:
0018             keys.append(key)
0019     for key in keys:
0020         if key in dict2:
0021             if key not in dict1 or dict1[key] is None:
0022                 dict1[key] = dict2[key]
0023             else:
0024                 if dict2[key] is None:
0025                     continue
0026                 elif isinstance(dict1[key], type(dict2[key])):
0027                     raise Exception("type of %s is different from %s, cannot merge" % (type(dict1[key]), type(dict2[key])))
0028                 elif dict1[key] == dict2[key]:
0029                     continue
0030                 elif type(dict1[key]) in (list, tuple, str):
0031                     dict1[key] = dict1[key] + dict2[key]
0032                 elif type(dict1[key]) in (int, float, complex):
0033                     dict1[key] = dict1[key] + dict2[key]
0034                 elif type(dict1[key]) in (bool, bool):
0035                     dict1[key] = True
0036                 elif type(dict1[key]) in (dict, dict):
0037                     dict1[key] = merge_dict(dict1[key], dict2[key])
0038     return dict1
0039 
0040 
0041 if __name__ == '__main__':
0042     a = {'a': 1, 'b': 2, 'c': [1, 2], 'd': {'a': 1, 'c': [4, 5]}, 'f': 1332}
0043     b = {'a': 3, 'b': 4, 'c': [3, 4], 'd': {'b': 1, 'c': [6, 5]}, 'e': 'abd'}
0044     print(id(a))
0045     print(id(b))
0046     c = merge_dict(a, b)
0047     print(id(c))
0048     print(c)