Codenoob
Codenoob

Reputation: 3

Appending dictionary to list with different value same key

I have a list of dictionaries, that have same keys and some have different values for those keys. I am trying to append the dictionaries that have different values from the list to keep track of the different values and I would concatenate the values of other keys. For example, I am storing 'a' keys with same values and concatenating the 'b' values that have same 'a':'1'

input list: d = [{'a': '1', 'b': '3'}, {'a': '2', 'b': '4'}, {'a': '1', 'b':'5'}]
output list: p = [{'a':'1', 'b': '35'}, {'a': '2', 'b': '4'}]

So far, I tried the following code, but it doesnt recognize the different values

length = len(p)
j = 0
for i in d:
    while j < length:
        if p[j]['a'] is not i['a']:
            p.append({'a', p[j]['a']})
        else:
            p[j]['b'] += i['b']
        j += 1
    j = 0
    

any tips would be appreciated

Upvotes: 0

Views: 102

Answers (1)

Barmar
Barmar

Reputation: 782498

Use a dictionary that has the a values as its keys so you don't have to loop through the result list for a matching a.

temp_dict = {}
for item in d:
    if item['a'] in temp_dict:
        temp_dict[item['a']]['b'] += item['b']
    else:
        temp_dict[item['a']] = item.copy()
p = list(temp_dict.values())

Upvotes: 1

Related Questions