1

I'm trying to update a specific item in a list of dictionaries based on another value

I have the list of dictionaries

Product_id= [{ "id": 342, "count": 10 },
{"id":  345, "count":  20 },
{"id":  546, "count": 30 },
{"id":  324, "count": 40 },
{"id":  789, "count": 50 },
{"id":  675, "count": 60 }]

I'd like to increase the "count" of x "id" where "id" == x

For example if "id" == 342 I want to increase the count by 1 so output would be

print(Product_id)

[{ "id": 342, "count": 11 },
{ "id":  345, "count":  20 },
{ "id":  546, "count": 30 },
{"id":  324, "count": 40 },
{"id":  789, "count": 50 },
{"id":  675, "count": 60 }]

I can bring up the counts but can update() the count...

I've already tried many things and searching stacks etc (and I know my last attempt was way off, below) so any ideas would be welcome

for d in Product_id:
    d.update((k + 1, "count") for k, v in d.items() if v\["id"\] == 342)
Kris
  • 8,680
  • 4
  • 39
  • 67
  • Others have indicated how to do the update, I'll just remark that a list of dicts may not be optimal here. For example, there could be dicts with duplicate ids. Why don't you create a single dictionary with `id` as the key? – Jussi Nurminen Apr 04 '22 at 10:19

4 Answers4

2

Answer:

There is a really nice and pythonic related answer to your question here --> Add an element in each dictionary of a list (list comprehension)

I would approach this using a list comprehesions in python for both readability and for writting succing/pythonic code:

In 1 line:

p_id = [{**dct,**{'count':dct[k]+1}} if dct['id']==342 else dct for dct in Product_id]

If you want a slightly more adaptable verison for use in a function etc:

# let x be the value that you want to upate
x = 342
# and k be the key of that value
k = 'count'
p_id = [{**dct,**{k:dct[k]+1}} if dct['id']==x else dct for dct in Product_id]

Explanation:

  1. Using if else statemets in list comprehension to return modified {'key' : 'value'} pair value if condition is true and simply return the dictionary if it flase.
  2. You can't assing variables from within list comp as in value+=1, howevever flattend form (using both if and else) is still less verbose than non list comprehesion form.
  3. **{} merges to dictionaris with right most replacing the key vluee pari of 'count' this is equivalent:
p_id = [dict(dct,**{k:dct[k]+1}) if dct['id']==x else dct for dct in Product_id]

Which will produce the same result and you may prefer. With the left most items where condition is true, if this evaluetes to false then dict if simplyt returned. 4. Star star ** unpacks the dictionary, see --> What does ** (double star/asterisk) and * (star/asterisk) do for parameters? 5. This this in longer form is eqivalent to:

p_id = [{'id':dct['id'],'count':dct['count']+1} if dct['id']==x else dct for dct in Product_id]

6 Rightmost item is the for loop itself and replaces:

for item in itterable:
    if some_condition:
        #do some stuff
fdsig
  • 268
  • 2
  • 5
1

As you have a list of dictionaries, you can loop through each dictionary in the list. After this, find the id of interest(here it is 342). Then increment the count of that dictionary by 1.

This is how you can do it:

Product_id= [{ "id": 342, "count": 10 },
{"id":  345, "count":  20 },
{"id":  546, "count": 30 },
{"id":  324, "count": 40 },
{"id":  789, "count": 50 },
{"id":  675, "count": 60 }]

x = 342
for item in Product_id:
    if item["id"] == x:
        item["count"] += 1 
        # You can add a break here if there's only one item to update. 

Output:

[{'id': 342, 'count': 11}, {'id': 345, 'count': 20}, {'id': 546, 'count': 30}, {'id': 324, 'count': 40}, {'id': 789, 'count': 50}, {'id': 675, 'count': 60}]
Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27
  • This will work although I would add a *break* after the value increment **unless** there's a possibility of more dictionaries with the same 'id' – DarkKnight Apr 04 '22 at 10:14
0

My suggestion:

for dic in Product_id:
    if dic["id"] == id:
         dic["count"] += 1
Schnitte
  • 1,193
  • 4
  • 16
  • Thank you so much for your assistance! It's exactly what I was looking for :) I knew it was a for loop but didn't know how to execute it properly! – user18700386 Apr 04 '22 at 23:52
0

You need to loop over the entire list of dictionaries and check the element that satisfies your condition.

for p in Product_id:
    if p['id'] == 342:
        p['count']+=1
    
print(Product_id)
Daniyal Ishfaq
  • 247
  • 1
  • 7
  • Thank you so much for your assistance! It's exactly what I was looking for :) I knew it was a for loop but didn't know how to execute it properly! – user18700386 Apr 04 '22 at 23:52