Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset all values in a dictionary

{"green": 0, "y3": 1, "m@tt": 0, "newaccount": 0, "egg": 0, "results": 0, "dan": 0, "Lewis": 0, "NewAccount2": 0, "testyear3": 1, "testyear6": 0, "NewAccount1": 0, "testyear4": 0, "testyear5": 0, "Matt1": 0, "swag": 1, "lewis": 1, "matt": 1, "notin": 0}

this is the dictionary defined as 'completeddict'. What I want to do, is to change ALL values no matter what they are called to 0. However bear in mind that new account names will be added at any point as 'keys' so I cannot manually do "completeddict[green] = 0", "completeddict[lewis] = 0", etc etc.

Is there any way to have python change ALL values within a dictionary back to 0?

EDIT: Unfortunately I do not want to create a new dictionary - I want to keep it called 'completeddict' as the program needs to use the dictionary defined as 'completeddict' at many points in the program.

like image 684
user3112327 Avatar asked Apr 10 '14 15:04

user3112327


People also ask

How do you clean up a dictionary in Python?

Python has in-built clear() method to delete a dictionary in Python. The clear() method deletes all the key-value pairs present in the dict and returns an empty dict.

How do you update a list of values in a dictionary?

Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')

Can you update an empty dictionary?

NO, calling update() with no parameters or with an empty dictionary will not change any of the existing key/values in the dictionary. The following code example shows both types of empty updates. The existing dictionary remains unchanged.


2 Answers

Another option is to use .fromkeys():

fromkeys(seq[, value])

Create a new dictionary with keys from seq and values set to value.

d = d.fromkeys(d, 0)

Demo:

>>> d = {"green": 0, "y3": 1, "m@tt": 0, "newaccount": 0, "egg": 0, "results": 0, "dan": 0, "Lewis": 0, "NewAccount2": 0, "testyear3": 1, "testyear6": 0, "NewAccount1": 0, "testyear4": 0, "testyear5": 0, "Matt1": 0, "swag": 1, "lewis": 1, "matt": 1, "notin": 0}
>>> d.fromkeys(d, 0)
{'newaccount': 0, 'swag': 0, 'notin': 0, 'NewAccount1': 0, 'Matt1': 0, 'testyear4': 0, 'Lewis': 0, 'dan': 0, 'matt': 0, 'results': 0, 'm@tt': 0, 'green': 0, 'testyear5': 0, 'lewis': 0, 'NewAccount2': 0, 'y3': 0, 'testyear3': 0, 'egg': 0, 'testyear6': 0}
like image 72
alecxe Avatar answered Oct 15 '22 16:10

alecxe


If you don't want to create a new dict, it seems like all you need is a simple two-line loop, unless I'm missing something:

for key in completeddict.keys():
    completeddict[key] = 0
like image 25
Bryan Oakley Avatar answered Oct 15 '22 15:10

Bryan Oakley