Dictionary Getting Overwritten in While Loop

python get all values from nested dictionary
iterate through nested dictionary python
while loop dictionary python
python dictionary
python add to dictionary in loop
python update dictionary in loop
python dictionary comprehension
iterate list of dictionaries python
def get_list_expenses():
  expense_list = {}
  print('Please type the name of the expense followed by the price of the expense')
  while True:
    name = input('Name of expense: ')
    price = int(input('Price of expense: '))
    expense_list.update({
        'name': name,
        'price': price,
    })
    cont = input('Want to add another? [y/n] ').lower()
    if cont == 'n':
        break
 print(type(expense_list))
 print(expense_list)
 return expense_list

Input ==========================
Please type the name of the expense followed by the price of the expense
Name of expense: Food
Price of expense: 100
Want to add another? [y/n] y
Name of expense: Car Insurance
Price of expense: 200
Want to add another? [y/n] n

Output =========================
<class 'dict'>
{'name': 'car', 'price': 200}

I'm new to python and wanted to try and make a budget application to save me time manually inputting information to excel. My idea was to create a loop that would take in the name of an expense and the price per month of it. I wanted to put this into a dictionary so I could .get the information whenever I needed it. However, my dictionary keeps getting overwritten. I've tried a few different solutions I can find online but nothing worked. Thanks in advance.


Using the update method on a dictionary you are basically rewriting the dictionary from scratch at every iteration, for this reason you see a single value at the end (the last one).

I would suggest to create an empty list and then append a new dictionary of values at every iteration:

def get_list_expenses():
  expense_list = []
  print('Please type the name of the expense followed by the price of the expense')
  while True:
    name = input('Name of expense: ')
    price = int(input('Price of expense: '))
    expense_list.append({
        'name': name,
        'price': price,
    })
    cont = input('Want to add another? [y/n] ').lower()
    if cont == 'n':
        break
 print(type(expense_list))
 print(expense_list)
 return expense_list

Different ways to Iterate / Loop over a Dictionary in Python , Creating Dictionaries with string as key and int as value. ''' Iterate over the dictionary using for loop over keys | “for in dictionary” Subscribe with us to join 1500+ Python & C++ developers, to get more Tips & Tutorials like this. Python : How to Remove multiple keys from Dictionary while Iterating ? Suppose you want to iterate through a dictionary in Python, but you need to iterate through it repeatedly in a single loop. To get this task done, you can use itertools.cycle(iterable), which makes an iterator returning elements from iterable and saving a copy of each.


expense_list.update({
    'name': name,
    'price': price,
})

Should be:

expense_list.update({name,price})

Simple Python, The first part of the program sets up a dictionary called champions containing This is followed by an indefinite while loop that will continuously re-run the If the user has typed in something, the champions.get() method either assigns None or then the value to which it refers will simply be overwritten with the new value. Running a for-loop over a Jinja2 dictionary At the time of this posting, iterating over dictionaries inside a Jinja template is poorly documented, especially if you need access to the jinja dictionary keys and it's something I end up doing alot.


Dictionary is a key value pair. In your case key will be 'Name of expense' and value will be price. The way you are creating you have 2 keys in dictionary. 1st key is 'name' and second key is 'price'.

You can simply do:

expense_list[name] = price

If name exists it will update otherwise will add.

Python Nested Dictionary, Learn to create a Nested Dictionary in Python, access change add and remove To avoid such exception, you can use the special dictionary get() method. Note that this method blindly overwrites values of the same key if there's a clash. Here the 'emp2′ record is updated while 'emp3′ is added to the dictionary. Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value, so that they can be retrieved efficiently.. Let’s discuss various ways of accessing all the keys along with their values in Python Dictionary.


Make expense_list an actual list:

expense_list = []

and then append to it

expense_list.append({
    'name': name,
    'price': price,
    })

Python Dictionary, Learn to create a Dictionary in Python, add remove access and change To avoid such exception, you can use the special dictionary get() method. Note that this method blindly overwrites values of the same key if there's a clash. To iterate over the values of a dictionary, index from key to value inside the for loop. Python Dictionary – Get Keys as List Dictionary is a collection of key:value pairs. You can get all the keys in the dictionary as a Python List. dict.keys() returns an iterable of type dict_keys(). You can convert this into a list using list(). Also, you can use * operator, which unpacks an iterable. Unpack dict or dict.keys() in using * operator. It creates a list with dictionary keys in it


How to Iterate Through a Dictionary in Python – Real Python, __iter__() on that dictionary, and you'll get an iterator over its keys: That is, if you modify any of them ( k or v ) directly inside the loop, then what really happens​  The fact is that your session variable gets overwritten everytime for as long as the while loop runs. Therefore only the last value from the loop is saved to the session array.


Python Dictionaries, It covers how to create a dictionary, how to access its elements, delete Elements stored in a dictionary can be accessed just like lists in python, i.e, using the for loop. However, while iterating over each element, we will get the key and not the The common values of both the lists get overwritten by the latter dictionary. I am acquiring event triggered data in a sequence structure with an embedded while loop. In this while loop I would like to acquire 2000 samples every time the acquisition loop is triggered for as many times as it is triggered. My output format is a text file and the vi is working great except for the fact that if I trigger the loop more than once, I still only get 2000 scans in my text file


Looping to Create Nested Dictionary, My code reads the lines and turns it into a nested dictionary. Currently, the code seems to be looping and overwriting the key values of the inner dictionary. Is there a way to get all of the indices excluding parts[1]? While in-loop code makes the most sense of what I have seen above, separating file  Python Dictionary pop() The pop() method removes and returns an element from a dictionary having the given key.