修改字典的所有键 [英] Altering all keys of a dictionary
问题描述
是否可以重命名/更改字典的所有键?作为示例,让我们看一下以下字典:
a_dict = {'a_var1':0.05,'a_var2':4.0,'a_var3':100.0,'a_var4':0.3}
我想删除键中的所有 a _
,所以我最终得到了
a_dict = {'var1':0.05,'var2':4.0,'var3':100.0,'var4':0.3}
如果您想更改现有的字典,而不是创建一个新的字典,可以循环键, pop
旧的,然后插入具有旧值的新的,经过修改的密钥.
>>>对于列表中的k(a_dict):... a_dict [k [2:]] = a_dict.pop(k)...>>>a_dict{'var2':4.0,'var1':0.05,'var3':100.0,'var4':0.3}
(对 list(a_dict)
进行迭代将防止由于并发修改而导致的错误.)
严格来说,这也不会更改现有密钥,而是插入新密钥,因为它必须根据其新的哈希码重新插入它们.但这确实改变了整个字典.
如注释中所述,实际上,循环更新字典中的键可能比对字典的理解要慢.如果存在问题,您还可以使用dict理解来创建新的dict,然后
清除
现有的dict并 update
使用新值. >>>b_dict = {k [2:]:a_dict中的k用a_dict [k]}>>>a_dict.clear()>>>a_dict.update(b_dict)
Is it possible to rename/alter all the keys of a dict? As an example, let's look at the following dictionary:
a_dict = {'a_var1': 0.05,
'a_var2': 4.0,
'a_var3': 100.0,
'a_var4': 0.3}
I want to remove all the a_
in the keys, so I end up with
a_dict = {'var1': 0.05,
'var2': 4.0,
'var3': 100.0,
'var4': 0.3}
If you want to alter the existing dict, instead of creating a new one, you can loop the keys, pop
the old one, and insert the new, modified key with the old value.
>>> for k in list(a_dict):
... a_dict[k[2:]] = a_dict.pop(k)
...
>>> a_dict
{'var2': 4.0, 'var1': 0.05, 'var3': 100.0, 'var4': 0.3}
(Iterating a list(a_dict)
will prevent errors due to concurrent modification.)
Strictly speaking, this, too, does not alter the existing keys, but inserts new keys, as it has to re-insert them according to their new hash codes. But it does alter the dictionary as a whole.
As noted in comments, updating the keys in the dict in a loop can in fact be slower than a dict comprehension. If this is a problem, you could also create a new dict using a dict comprehension, and then clear
the existing dict and update
it with the new values.
>>> b_dict = {k[2:]: a_dict[k] for k in a_dict}
>>> a_dict.clear()
>>> a_dict.update(b_dict)
这篇关于修改字典的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!