Ficik
Ficik

Reputation: 13

Merge dictionaries in a list of dictionaries by combining the values

Help me please. I have query set from Model.objects.value('name', 'language__name') and it give me the list of dictionary:

list = [{'id': 1, 'name': 'Adel', 'language': 'С#'},
{'id': 1, 'name': 'Adel', 'language': 'Python'},
{'id': 5, 'name': 'Dora', 'language': 'С#'},
{'id': 5, 'name': 'Dora', 'language': 'Java'},
{'id': 6, 'name': 'Dars', 'language': 'Python'}];

how can I to do a list of dictionary but to unit key and value? I want to get like this:

list = [{'id': 1, 'name': 'Adel', 'language':['С#','Python']},
{'id': 5, 'name': 'Dora', 'language': ['С#','Java']},
{'id': 6, 'name': 'Dars', 'language': 'Python'}];

I tried this:

mapping = {} 
for d in qs: 
    try: 
        entry = mapping[d['id']] # raises KeyError 
        entry['language__name'].append(d['language__name']) # raises AttributeError 
    except KeyError: 
        mapping[d['id']] = d 
    except AttributeError: 
        entry['language__name'] = [entry['language__name'], d['language__name']] 
        
print(list(mapping.values()))

Upvotes: 0

Views: 928

Answers (1)

user7864386
user7864386

Reputation:

You can iterate over lst and create a dictionary out where the keys correspond to "id" values in the dicts in lst and the values are dicts. In each iteration, check if the value under "language" key is a list or not and append to the list if it's a list, create a list, if not. Finally, pass the values of out to a list constructor for the final outcome.

out = {}
for d in lst:
    if d['id'] in out:
        if isinstance(out[d['id']]['language'], list):
            out[d['id']]['language'].append(d['language'])
        else:
            out[d['id']]['language'] = [out[d['id']]['language'], d['language']]
    else:
        out[d['id']] = d
out = list(out.values())

Output:

[{'id': 1, 'name': 'Adel', 'language': ['С#', 'Python']},
 {'id': 5, 'name': 'Dora', 'language': ['С#', 'Java']},
 {'id': 6, 'name': 'Dars', 'language': 'Python'}]

Upvotes: 2

Related Questions