app/soc/logic/dicts.py
changeset 900 0b416bb14970
parent 744 cd9bf163473c
child 1307 091a21cf3627
equal deleted inserted replaced
899:91a43d0aa29a 900:0b416bb14970
    41       result[key] = value
    41       result[key] = value
    42   
    42   
    43   return result
    43   return result
    44 
    44 
    45 
    45 
    46 def merge(target, updates):
    46 def merge(target, updates, sub_merge=False, recursive=False):
    47   """Like the builtin 'update' method but does not overwrite existing values.
    47   """Like the builtin 'update' method but does not overwrite existing values.
    48 
    48 
    49   Args:
    49   Args:
    50     target: The dictionary that is to be updated, may be None
    50     target: The dictionary that is to be updated, may be None
    51     updates: A dictionary containing new values for the original dict
    51     updates: A dictionary containing new values for the original dict
       
    52     sub_merge: Merge a dict or list present in both target and update
       
    53     recursive: Determines whether merge_subdicts is recursive
    52 
    54 
    53   Returns:
    55   Returns:
    54     the target dict, with any missing values from updates merged in, in-place.
    56     the target dict, with any missing values from updates merged in, in-place.
    55   """
    57   """
    56 
    58 
    58     target = {}
    60     target = {}
    59 
    61 
    60   for key, value in updates.iteritems():
    62   for key, value in updates.iteritems():
    61     if key not in target:
    63     if key not in target:
    62       target[key] = value
    64       target[key] = value
       
    65     elif sub_merge:
       
    66       target_value = target[key]
       
    67 
       
    68       # try to merge dicts
       
    69       if isinstance(value, dict) and isinstance(target_value, dict):
       
    70         # the merge becomes recursive by specifying it not only as value
       
    71         # to sub_merge but also to recursive
       
    72         target[key] = merge(target_value, value,
       
    73                             sub_merge=recursive, recursive=recursive)
       
    74 
       
    75       # try to merge lists
       
    76       if isinstance(value, list) and isinstance(target_value, list):
       
    77         target[key] = target_value + value
    63 
    78 
    64   return target
    79   return target
    65 
    80 
    66 
    81 
    67 def zip(keys, values):
    82 def zip(keys, values):