[英]modifiy values of multiple keys at once in python dictionary
Is it possible to change the values of multiple keys at once without the loop?是否可以在没有循环的情况下一次更改多个键的值?
d = {1: 0, 2: 0, 3: 0}
for k in [1,2]:
d[k] += 1
If all you want to do is replace values, then you can use dict.update
:如果您只想替换值,那么您可以使用dict.update
:
d = {1:0, 2:0, 3:0}
d.update({1:1, 2:1})
# {1: 1, 2: 1, 3: 0}
but as far as I know, there's no way to make a custom change without using a loop of some sort.但据我所知,如果不使用某种循环,就无法进行自定义更改。 You could use a list comprehension to make a new dict to feed to .update()
, doing it all in one line:您可以使用列表理解来创建一个新的 dict 来提供给.update()
,在一行中完成所有操作:
d.update({k: d[k] + 1 for k in [1, 2]})
but I don't think there's a general solution for modifying the dict in-place in this way.但我不认为有一个通用的解决方案来以这种方式就地修改 dict。
应该能够使用字典的更新方法,只需包含您要更新的键和您希望它们具有的值。
mydict.update(dict(zip(keys, mytupleValues))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.