Home > Software design >  updating items in list of dictionaries
updating items in list of dictionaries

Time:04-04

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)

CodePudding user response:

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}]

CodePudding user response:

My suggestion:

for dic in Product_id:
    if dic["id"] == id:
         dic["count"]  = 1

CodePudding user response:

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)

CodePudding user response:

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
  • Related