Rename a dictionary key

2019-01-03 08:01发布

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.

6条回答
老娘就宠你
2楼-- · 2019-01-03 08:32

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(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. 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.

查看更多
该账号已被封号
3楼-- · 2019-01-03 08:33

best method in 1 line:

>>> d = {'test':[0,1,2]}
>>> d['test2'] = d.pop('test')
>>> d
{'test2': [0, 1, 2]}
查看更多
疯言疯语
4楼-- · 2019-01-03 08:44

Using a check for newkey!=oldkey, this way you can do:

if newkey!=oldkey:  
    dictionary[newkey] = dictionary[oldkey]
    del dictionary[oldkey]
查看更多
叼着烟拽天下
5楼-- · 2019-01-03 08:49

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:

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
查看更多
放我归山
6楼-- · 2019-01-03 08:52

Other answers are pretty good.But in python3.6, regular dict also has order. So it's hard to keep key's position in normal case.

def rename(old_dict,old_name,new_name):
    new_dict = {}
    for key,value in zip(old_dict.keys(),old_dict.values()):
        new_key = key if key != old_name else new_name
        new_dict[new_key] = old_dict[key]
    return new_dict
查看更多
我想做一个坏孩纸
7楼-- · 2019-01-03 08:54

A few people before me mentioned the .pop trick to delete and create a key in a one-liner.

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}

查看更多
登录 后发表回答