重命名字典键

本文翻译自:Rename a dictionary key

Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; 有没有一种方法可以重命名字典键,而无需将其值重新分配给新名称并删除旧名称键; and without iterating through dict key/value? 而不迭代字典键/值?

In case of OrderedDict, do the same, while keeping that key's position. 对于OrderedDict,在保持键的位置的同时执行相同的操作。


#1楼

参考:https://stackoom.com/question/17800/重命名字典键


#2楼

Using a check for newkey!=oldkey , this way you can do: 使用newkey!=oldkey的检查,可以这样:

if newkey!=oldkey:  
    dictionary[newkey] = dictionary[oldkey]
    del dictionary[oldkey]

#3楼

For a regular dict, you can use: 对于常规字典,可以使用:

mydict[new_key] = mydict.pop(old_key)

For an OrderedDict, I think you must build an entirely new one using a comprehension. 对于OrderedDict,我认为您必须使用一种理解来构建一个全新的。

>>> OrderedDict(zip('123', 'abc'))
OrderedDict([('1', 'a'), ('2', 'b'), ('3', 'c')])
>>> oldkey, newkey = '2', 'potato'
>>> OrderedDict((newkey if k == oldkey else k, v) for k, v in _.viewitems())
OrderedDict([('1', 'a'), ('potato', 'b'), ('3', 'c')])

Modifying the key itself, as this question seems to be asking, is impractical because dict keys are usually immutable objects such as numbers, strings or tuples. 正如这个问题似乎提出的那样,修改密钥本身是不切实际的,因为dict密钥通常是不可变的对象,例如数字,字符串或元组。 Instead of trying to modify the key, reassigning the value to a new key and removing the old key is how you can achieve the "rename" in python. 您可以尝试在python中实现“重命名”,而不是尝试修改键,而是将值重新分配给新键并删除旧键。


#4楼

You can use this OrderedDict recipe written by Raymond Hettinger and modify it to add a rename method, but this is going to be a O(N) in complexity: 您可以使用由Raymond Hettinger编写的OrderedDict recipe ,并对其进行修改以添加rename方法,但这在复杂度上将是O(N):

def rename(self,key,new_key):
    ind = self._keys.index(key)  #get the index of old key, O(N) operation
    self._keys[ind] = new_key    #replace old key with new key in self._keys
    self[new_key] = self[key]    #add the new key, this is added at the end of self._keys
    self._keys.pop(-1)           #pop the last item in self._keys

Example: 例:

dic = OrderedDict((("a",1),("b",2),("c",3)))
print dic
dic.rename("a","foo")
dic.rename("b","bar")
dic["d"] = 5
dic.rename("d","spam")
for k,v in  dic.items():
    print k,v

output: 输出:

OrderedDict({'a': 1, 'b': 2, 'c': 3})
foo 1
bar 2
c 3
spam 5

#5楼

best method in 1 line: 1行中的最佳方法:

>>> d = {'test':[0,1,2]}
>>> d['test2'] = d.pop('test')
>>> d
{'test2': [0, 1, 2]}

#6楼

A few people before me mentioned the .pop trick to delete and create a key in a one-liner. 在我之前的一些人提到了.pop技巧,该技巧可以删除并创建单行密钥。

I personally find the more explicit implementation more readable: 我个人认为更明确的实现更具可读性:

d = {'a': 1, 'b': 2}
v = d['b']
del d['b']
d['c'] = v

The code above returns {'a': 1, 'c': 2} 上面的代码返回{'a': 1, 'c': 2}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值