How to modify the values of a dictionary from a list of dictionaries

Roy

I am declaring a method named add_to_cart(db, itemid, quantity). Whenever the method is called, it will look into the database for the session data. Session data contains a list of dictionaries. The purpose of this method is to create a new entry (dictionary) to the list or update the value of existing entry. Dictionary has the following keys: id, quantity

So far I have developed the following code. First of all after fetching the data from the database, I am matching the itemid with the dictionary key: 'id'. If the itemid does not match with any of the values of the dictionaries, then it will append a new dictionary to that list.

def add_to_cart(db, itemid, quantity):
    # ......
    row = cursor.fetchone()
    if row is not None:
        cart = json.loads(row['data'])
        for dic in cart:
            if str(dic.get("id")) == str(itemid):
                dic['quantity'] = int(dic['quantity']) + quantity
                data = json.dumps(cart)
                # update the 'data' to the database
                break
     else:
         if counter == len(cart):
              item = {
                      'id': itemid,
                      'quantity': quantity
                     }
              cart.append(item)
              data = json.dumps(cart)  
              # update the 'data' to the database
              break

Let the initial cart is like:

[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]

When I add 1 more of the item 40 to the cart, this should be like:

[{'id': '40', 'quantity': '3'}, {'id': '41', 'quantity': '5'}]

but I am getting :

[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}, {'id': '40', 'quantity': '1'}]

Devesh Kumar Singh

You are adding a new dictionary to the list when you do cart.append(item), hence the list
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]

ends up being

[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}, {'id': '40', 'quantity': '1'}]

But you want to find the matching id in that list of dictionaries, and add to the quantity for that dictionary.

So the code will look like as below:

li = [{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]

def add_elem(li, id, to_add):

    #Iterate over the dictionaries
    for item in li:
        #If the id is found
        if str(id) in item.values():
            #Increment the quantity
            item['quantity'] = str(int(item['quantity']) + to_add)

    #Return the updated list
    return li

print(add_elem(li, 40, 1))

The output will be

[{'id': '40', 'quantity': '3'}, {'id': '41', 'quantity': '5'}]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how to print dictionary values in a list of dictionaries?

change dictionary values to dictionaries from list of dictionaries in python

How to sort dictionaries and create a dictionaries based on the values in the list inside the dictionary

How to add values from dictionaries in another dictionary?

How to create list of dictionaries from a single dictionary?

How to delete a dictionary from a list of dictionaries?

How to create a list of dictionaries from a dictionary

How to convert a list of dictionaries, within a dictionary, to a list of just values?

How to create three separate lists of values from a list of dictionaries where each dictionary has three keys

dictionary of values/lists to list of dictionaries

trying to delete duplicate dictionary values from the list of dictionaries

Comparing 2 dictionaries in python and create a list with values from dictionary

Creating a dictionary with multiple values per key from a list of dictionaries

Create a dictionary from list of dictionaries selecting specific values

How to get the values from a list of dictionaries and append

How to get unique values from a list of dictionaries?

How to drop dictionaries with NaN values from list

How to get values from list of nested dictionaries?

How to create new dictionary from multiple dictionaries when values from one dictionary are keys in other dictionaries?

Extract values from dictionary of dictionaries

How to merge values of dictionaries with same key into one from a list of dictionaries?

How to get specific values from a dictionary using list comprehension and modify them?

From list of dictionaries of dictionary to dataframe

create a list of dictionaries from a dictionary

list of dictionaries from single dictionary

Using dictionary to modify list values

How to store dictionary values into an array from array of dictionaries in swift

how to obtain dictionary of dictionaries that stores aggregated values from a csv file

How to remove the duplicate dictionaries from the list of dictionaries where dictionary contains an another dictionary?