Alo
Alo

Reputation: 67

how to divide values of list of dicts by number?

a = [{"language": "en-US", "count": 10}, {"language": "en", "count": 3}]

I would like to divide the values of the field count by the sum of all counts in this list.

The given result should be: count/ sum(counts)

a = [{"language": "en-US", "count": 0.76}, {"language": "en", "count": 0.23}]

I was able to calculate the sum of count values:

total_count = sum(d.get('count', 0) for d in a)

Upvotes: 0

Views: 81

Answers (3)

Maxime Bouhadana
Maxime Bouhadana

Reputation: 458

You have a type error: you need to convert these count values to integers.

Try this:

a =[{ "language": "en-US", "count": "10" }, { "language": "en", "count": "3" }]


total = sum(int(item["count"]) for item in a)
# retrieves the value count for each dictionary of a

for item in a :
    item["count"] = str(round(int(item["count"])/total), 2)
    # replace the old count with your actual count (divided by the total)

Upvotes: 0

Blackgaurd
Blackgaurd

Reputation: 658

Here is an answer that more closely resembles the OP's requirements.

As the other answers have stated, you need to convert the numbers from strings to ints. After that, you can use an f-string to format the floats to 2 decimal places.

a = [{"language": "en-US", "count": "10"}, {"language": "en", "count": "3"}]
total_count = sum(int(d.get("count", 0)) for d in a)
for d in a:
    d["count"] = f"{int(d.get('count', 0)) / total_count :.2f}"

Upvotes: 0

SCcagg5
SCcagg5

Reputation: 647

you could scroll thought your list and edit the values:

a =[{ "language": "en-US", "count": "10" }, { "language": "en", "count": "3" }]
total_count = sum(int(d.get('count', 0)) for d in a)
for data in a:
  data['count']  = int(data['count']) / total_count

Upvotes: 1

Related Questions