Home > Back-end >  How to get individual fields in list of dictionary
How to get individual fields in list of dictionary

Time:07-21

I have a list of dictionaries called dictList that has data like so: [{'id': '5', 'total': '39'}, {'id': '5', 'total': '43'}].

I am trying to create a new dictionary that uses the id as the key and total as the value.

So have tried this:

keys = [d['id'] for d in dictList]
values = [d['total'] for d in dictList]

new_dict[str(keys)]= values

However the output is: {"['5', '5']": [39, 43]}

I am not sure what is going on, I am just trying to get the id and the respective total like 5, 39 and 5, 43 in to new_dict.

EDIT: Please note that dictList contains all the products with ID 5. There are other fields, but I didn't include them.

CodePudding user response:

One approach:

data = [{'id': '5', 'total': '39'}, {'id': '5', 'total': '43'}]

res = {}
for d in data:
    key = d["id"]
    if key not in res:
        res[key] = 0
    res[key]  = int(d["total"])

print(res)

Output

{'5': 82}

Alternative using collections.defaultdict:

from collections import defaultdict

data = [{'id': '5', 'total': '39'}, {'id': '5', 'total': '43'}]

res = defaultdict(int)
for d in data:
    key = d["id"]
    res[key]  = int(d["total"])

print(res)

Output

defaultdict(<class 'int'>, {'5': 82})

CodePudding user response:

Use sorted and itertools.groupby to group by the 'id' key of each list element:

import itertools

dictList = [{'id': '5', 'total': '39'}, {'id': '10', 'total': '10'},
            {'id': '5', 'total': '43'}, {'id': '10', 'total': '22'}]

groups = itertools.groupby(sorted(dictList, key=lambda item: item['id'])
                           , key=lambda item: item['id'])

Next, take the sum of each group:

product_totals = {
    key: sum(int(item['total']) for item in grp)
    for key, grp in groups
}

Which gives:

{'10': 32, '5': 82}

CodePudding user response:

Although I'm not sure what you are trying to do, try this:

for d in dictlist:
    if new_dict[d["id"]]:
        new_dict[d["id"]]  = d["total"]
    else:
        new_dict[d["id"]] = d["total"]
  • Related