如何重置字典中的所有值 [英] How to reset all values in a dictionary

查看:152
本文介绍了如何重置字典中的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,dan:0,Lewis:0,NewAccount2:0,testyear3:1,testyear6:0,NewAccount1:0,testyear4:0,testyear5 Matt1:0,swag:1,lewis:1,matt:1,notin:0}

这是定义为completeddict的字典。
我想做的是改变所有的值,无论他们调用什么值为0.
但是请记住,新的帐号将被添加到任何一个键,所以我不能手动dodonedict [green] = 0,finisheddict [lewis] = 0等等。



有没有办法让python更改字典中的所有值返回0?



编辑:不幸的是我不想创建一个新的字典 - 我想保持它被称为completeddict,因为程序需要使用定义的字典作为程序中的许多点的完成。

解决方案

另一个选项是使用 .fromkeys()


fromkeys(seq [,value])



使用seq和值设置为值。




  d = d.fromke ys(d,0)

演示:

 >>> 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 ,lewis:1,matt:1,notin:0} 
>>> d.fromkeys(d,0)
{'newaccount':0,'swag':0,'notin':0,'NewAccount1':0,'Matt1':0,'testyear4' Lewis':0,'dan':0,'matt':0,'results':0,'m @ tt':0,'green':0,'testyear5':0,'lewis' NewAccount2':0,'y3':0,'testyear3':0,'egg':0,'testyear6':0}


{"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.

解决方案

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}

这篇关于如何重置字典中的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆