Existing dictionaries in list all being updated to new dictionary entry?

dictionary update
python update dictionary value list
python dictionary update if key exists
python update dictionary value by key
list of dictionaries python
python dictionary append
python dictionary methods
python dictionary of dictionaries

I am trying to create a simple program that contains a list of dictionaries. The grocery_history is the list of dictionaries, and the dictionary is grocery_item. Here is the code:

'''
The task is broken down into three sections.
Section 1 - User Input
Section 2 - loop through the grocery list
Section 3 - provide output to the console
'''


grocery_item = {}
grocery_history = []
stop = 'go'

while stop != 'q':
    item_name = input("Item name:\n")
    quantity = int(input("Quantity purchased:\n"))
    cost = float(input("Price per item:\n"))

    grocery_item['name'] = item_name
    grocery_item['number'] = quantity
    grocery_item['price'] = cost

    grocery_history.append(grocery_item)

    stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
    print(grocery_history)

grand_total = 0 

for grocery_item in range(0, len(grocery_history)):

  item_total = grocery_history[grocery_item]['number'] * grocery_history[grocery_item]['price']
  grand_total += item_total

  print(str(grocery_history[grocery_item]['number']) + " " + grocery_history[grocery_item]['name'] + " @ $%.2f" % grocery_history[grocery_item]['price'] + " ea \t$%.2f" % item_total)

  item_total = 0.0

print("Grand total: $%.2f" % grand_total)
print(grocery_history)

In case you're wondering, the prompt for this assignment told me to use the variable grocery_item in my for loop. I normally would have chosen a different name since it becomes confusing. I also added a couple of print statements to print out the contents of grocery_history to see what's going wrong, and I confirmed it's when the dictionary is being added to the grocery_history list, that's when it for some reason updates existing dictionary items to match the new one being added. I can't figure out what I'm doing wrong. Any help would be greatly appreciated!

You need to define a new dictionary object each time in loop or else you end up using the same dictionary object so in effect replaces the already added one.

while stop != 'q':
    grocery_item = {}
    # ...

Manipulating Lists and Dictionaries in Python, Of course, we can add that key and its corresponding value as a new element to the dictionary. To do that, we will use the .update() method as� A new word is entered in our dictionary when evidence shows it in frequent use by many writers. Usually, this process takes at least a few years, but there are extraordinary cases when a new term enters the language and immediately becomes part of our collective daily vocabulary. Such is the case with the language of the current pandemic.

sample code should work

grocery_history = []
stop = 'go'

while stop != 'q':
    item_name = input("Item name:\n")
    quantity = int(input("Quantity purchased:\n"))
    cost = float(input("Price per item:\n"))

    grocery_item = {}
    grocery_item['name'] = item_name
    grocery_item['number'] = quantity
    grocery_item['price'] = cost

    grocery_history.append(grocery_item)

    stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
    print(grocery_history)

grand_total = 0

for grocery_item in range(0, len(grocery_history)):

  item_total = grocery_history[grocery_item]['number'] * grocery_history[grocery_item]['price']
  grand_total += item_total

  print(str(grocery_history[grocery_item]['number']) + " " + grocery_history[grocery_item]['name'] + " @ $%.2f" % grocery_history[grocery_item]['price'] + " ea \t$%.2f" % item_total)

  item_total = 0.0

print("Grand total: $%.2f" % grand_total)
print(grocery_history)

the problem happened because you are repeating using same dict, although it adds to list each time, what you actually doing is keep updating the same reference so all content in the list becomes the same value move dict inside solve the problem

Python Dictionary update(), The update() method updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs. Python Lists � Dictionaries in Python List Methods � Dictionary Methods � String Methods � View all. Python dictionary. If the key is in the dictionary, it updates the key with the new value. Copy the entire dictionary to new dictionary: dict.copy() update() Update a dictionary by adding a new entry or a key-value pair to an existing entry or by deleting an existing entry. Dict.update([other]) items() Returns a list of tuple pairs (Keys, Value) in the dictionary. dictionary.items() sort() You can sort the elements: dictionary.sort() len()

This is because your loop does not create a new grocery_item object each time; it just updates the same grocery_item object over and over.

grocery_history ends up containing multiple references to this single object, in its latest state.

To fix this issue, move the line grocery_item = {} to be the first item underneath the while stop != 'q': loop. This will create a new object each time through the loop.

Python Dictionary, Check out what is a dictionary in Python, how to create, append, update, and delete as a list or a set which has a single value field, the dictionary type stores a key 1 Create Dictionaries; 2 Dictionary Operations; 3 Access Elements; 4 Append in You can append a new item to an existing dict object with elements in the� If you want the new dictionary to be used for another language, while the new dictionary is still selected in the Dictionary List, select the language on the Dictionary language menu. If you want your new custom dictionary to be the default dictionary, where any words you add will be saved, see the next task, Change the custom dictionary to

You can use map and sum to get grand_total

grocery_history = []
stop = 'go'

while stop != 'q':
    grocery_item = {}

    grocery_item['name'] = input("Item name:\n")
    grocery_item['number'] = int(input("Quantity purchased:\n"))
    grocery_item['price'] = float(input("Price per item:\n"))

    grocery_history.append(grocery_item)

    stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")

grand_total = sum(map(lambda item: item['number'] * item['price'], grocery_history))

print("Grand total: $%.2f" % grand_total)
print(grocery_history)

Input:

Item name:
item
Quantity purchased:
2
Price per item:
1.2
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
q

Output:

Grand total: $2.40
[{'name': 'item', 'number': 2, 'price': 1.2}]

Python Dictionary(Dict): Update, Cmp, Len, Sort, Copy, Items, str , Each key-value pair in the dictionary maps the key to its associated value Python List cmp() Method; Dictionary Str(dict); Merging Dictionaries a dictionary by adding a new entry or a key-value pair to an existing entry or by� List after deletion of dictionary : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 3, ‘data’: ‘Rash’}] Method #2 : Using list comprehension This method works by constructing the whole new or overwriting the original list by all the dictionaries except the one that has the key that has to be deleted.

Python Dictionary, GBlog � Puzzles � What's New? In Python Dictionary, update() method updates the dictionary with the elements Dictionary with elements from a dictionary object or an iterable object of key/value pairs. Python program to show working . The update() method adds element(s) to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value. If the key is in the dictionary, it updates the key with the new value.

How to update key and value in dictionary in python, You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry . Example: Output: You can only update the value and key cannot be updated. Updating key and value is nothing Are Python lists and dictionaries an important topic in coding? 3,942 Views. This explains why our global variables were changed when we were experimenting with lists and dictionaries earlier. Because lists and dictionaries are mutable, changing them (even inside a function) changes the list or dictionary itself, which isn’t the case for immutable data types.

Updates to the OED, The material added to the dictionary includes revised versions of existing entries (which again these new and updated entries are being made available free to all at oed.com. You can see the full list of words added in this update here. used in political circles recently, from former Oxford Dictionaries Word of the Year � Home Updates to the OED. Updates to the OED. The OED is updated on a quarterly basis, and the updates make up the Third Edition of the OED.The material added to the dictionary includes revised versions of existing entries (which replace the older versions), and new words and senses both within the alphabetical sequence of revised entries and also across the whole A to Z range.

Comments
  • Sorry, those comments were already there from the assignment prompt, I'll remove them from this post.
  • Ah okay, thanks. For some odd reason, the assignment prompt told me to create the empty dictionary at the top with the empty list instead of in the loop... I tried what you said and it worked.