how to merge same value dict of list

Question:

Here is my list of dictionary.

a = [{'ID': 1, 'FID': 938119, 'LEFT': 'A', 'LTIME': '1:10', 'RIGHT': '', 'RTIME': ''},
     {'ID': 2, 'FID': 938119, 'LEFT': 'B', 'LTIME': '1:55', 'RIGHT': '', 'RTIME': ''},
     {'ID': 3, 'FID': 938119, 'LEFT': '', 'LTIME': '', 'RIGHT': 'A', 'RTIME': '1:20'},
     {'ID': 4, 'FID': 938119, 'LEFT': 'A', 'LTIME': '1:56', 'RIGHT': '', 'RTIME': ''},
     {'ID': 5, 'FID': 938120, 'LEFT': 'A', 'LTIME': '1:36', 'RIGHT': '', 'RTIME': ''},
     ]

How can I get output like below:(Group by FID and LEFT, sum LTIME and RTIME)

b = [
    {'ID': 1, 'FID': 938119, 'LEFT': 'A', 'LTIME': '3:06', 'RIGHT': 'A', 'RTIME': '1:20'},
    {'ID': 2, 'FID': 938119, 'LEFT': 'B', 'LTIME': '1:55', 'RIGHT': '', 'RTIME': ''},
    {'ID': 3, 'FID': 938120, 'LEFT': 'A', 'LTIME': '1:36', 'RIGHT': '', 'RTIME': ''},
]
Asked By: happytimecq

||

Answers:

If I understood correctly what you’re trying to do, I think the following code solves your question:


from typing import List, Dict


def time_add(*times: List[str]) -> str:
    """Add times represented in string format "M:SS" together.

    Parameters:
    -----------
    *times : List[str]
        A list of times in string format.

    Returns:
    -------
    str
        A string representation of the sum in "M:SS" format.
        An empty string if the sum of times is equal to zero.

    Example:
    -------
    >>> time_add("1:20", "0:30")
    '1:50'

    >>> time_add("0:20", "0:30", "0:40")
    '1:30'

    >>> time_add("0:20", "-0:30", "0:40")
    '0:30'

    >>> time_add("0:20", "-0:30", "0:40")
    -0:30
    """
    total_time = 0
    for _time in times:
        if isinstance(_time, str) and ':' in _time:
            minutes, seconds = list(map(int, _time.split(':')))
            direction = -1 if '-' in _time else 1
            total_time += minutes * 60 + seconds * direction
    if total_time == 0:
        return ''
    return f'{str(total_time/60).split(".")[0]}:{total_time%60:02d}'


def transform_list(input_list: List[Dict[str, str]]) -> List[Dict[str, str]]:
    """
    Transform a list of dictionaries into a new list of dictionaries.
    
    This function takes a list of dictionaries as input, and returns a new
    list of dictionaries that contains summarized information based on the `FID`
    value of each dictionary.
    If multiple dictionaries in the input list have the same `FID` value, then
    the resulting dictionary in the output list will contain the concatenated 
    values of the `LEFT` and `RTIME` keys, while the `ID` value will be the
    value of the first dictionary with that `FID` value.
    
    Parameters
    ----------
    input_list : List[Dict[str, str]]
        List of dictionaries to be transformed.
        Each dictionary must contain the keys: 'ID', 'FID', 'LEFT', 'LTIME', 
        'RIGHT', 'RTIME'.
    
    Returns
    -------
    List[Dict[str, str]]
        A new list of dictionaries that summarizes the information in the
        input list based on the `FID` value of each dictionary.
        Each resulting dictionary in the output list will contain
        the keys 'ID', 'FID', 'LEFT', 'LTIME', 'RIGHT', 'RTIME'.
    
    Examples
    --------
    >>> a = [{'ID': 1, 'FID': 938119, 'LEFT': 'A', 'LTIME': '1:10', 'RIGHT': '', 'RTIME': ''},
    ...      {'ID': 2, 'FID': 938119, 'LEFT': 'B', 'LTIME': '1:55', 'RIGHT': '', 'RTIME': ''},
    ...      {'ID': 3, 'FID': 938119, 'LEFT': '', 'LTIME': '', 'RIGHT': 'A', 'RTIME': '1:20'},
    ...      {'ID': 4, 'FID': 938119, 'LEFT': 'A', 'LTIME': '1:56', 'RIGHT': '', 'RTIME': ''},
    ...      {'ID': 5, 'FID': 938120, 'LEFT': 'A', 'LTIME': '1:36', 'RIGHT': '', 'RTIME': ''}]
    >>> transform_list(a)
    [{'ID': 1, 'FID': 938119, 'LEFT': 'A', 'LTIME': '3:06', 'RIGHT': 'A', 'RTIME': '1:20'},
    {'ID': 2, 'FID': 938119, 'LEFT': 'B', 'LTIME': '1:55', 'RIGHT': '', 'RTIME': ''},
    {'ID': 5, 'FID': 938120, 'LEFT': 'A', 'LTIME': '1:36', 'RIGHT': '', 'RTIME': ''}]
    """
    result = []
    fids_dict = {}
    
    for item in input_list:
        sub_key = item['LEFT'] if item['LEFT'] else item['RIGHT']
        fid = f"{item['FID']}_{sub_key}"
        if fid not in fids_dict.keys():
            fids_dict[fid] = {'ID': item['ID'], 'FID': int(fid.split('_')[0]),
                            'LEFT': item['LEFT'], 'LTIME': '0:0',
                            'RIGHT': item['RIGHT'], 'RTIME': ''}

        fids_dict[fid]['LEFT'] = item['LEFT'] if fids_dict[fid]['LEFT'] == '' else fids_dict[fid]['LEFT']
        fids_dict[fid]['RIGHT'] = item['RIGHT'] if fids_dict[fid]['RIGHT'] == '' else fids_dict[fid]['RIGHT']

        fids_dict[fid]['LTIME'] = time_add(fids_dict[fid]['LTIME'], item['LTIME'])
        fids_dict[fid]['RTIME'] = time_add(fids_dict[fid]['RTIME'], item['RTIME'])

    return list(fids_dict.values())


The transform_list function takes a list of dictionaries as input and returns a new list of dictionaries with summarized information based on the value of the "FID" key of each dictionary. It does so by creating a dictionary of dictionaries, where the keys of this dictionary are derived from the "FID" and "LEFT" or "RIGHT" keys of each input dictionary. The values of this dictionary are new dictionaries that store summarized information from the input dictionaries with the same "FID" and "LEFT" or "RIGHT" keys. Finally, it returns the values of this dictionary of dictionaries as a list of dictionaries.

Answered By: Ingwersen_erik
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.