Search code examples
pythonlistdictionarylist-comprehensiondictionary-comprehension

Python Combining Dictionary of A List having Same Characteristics


I have a list list like this

values = [{'id':1, 'x':2}, {'id':1, 'y':4}, {'id':1, 'z':6}, {'id':2, 'j':5}, {'id':2, 'k':10}, {'id':3, 'w':1}, {'id':3, 'x':3}, {'id':3, 'y':5}, {'id':3, 'z':7}]

I want the result to be a List with new Dict values(in most efficient way, if possible) like this:

values = [{'id':1, 'x':2, 'y':4, 'z':6}, {'id':2, 'j':5, 'k':10}, {'id':3, 'w':1, 'x':3, 'y':5, 'z':7}]

How should Loop for that kind of case.


Solution

  • Not beautiful solution, but working one

    values = [{'id': 1, 'x': 2}, {'id': 1, 'y': 4}, {'id': 1, 'z': 6},
              {'id': 2, 'j': 5},
              {'id': 2, 'k': 10}, {'id': 3, 'w': 1}, {'id': 3, 'x': 3},
              {'id': 3, 'y': 5}, {'id': 3, 'z': 7}]
    
    # get all unique possible keys
    unique_keys = set((x['id'] for x in values))
    result = []
    for value in unique_keys:
        new_dict = dict(id=value)
        for old_dict in values:
            if old_dict['id'] == value:
                new_dict.update(old_dict)
        result.append(new_dict)
    print(result)
    

    The printed result:

    {'id': 1, 'z': 6, 'x': 2, 'y': 4}, {'j': 5, 'id': 2, 'k': 10}, {'x': 3, 'y': 5, 'id': 3, 'w': 1, 'z': 7}]