{"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.
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.
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')
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.
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With