Rename a dictionary key

后端 未结 12 868
盖世英雄少女心
盖世英雄少女心 2020-11-22 16:54

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?

I

12条回答
  •  佛祖请我去吃肉
    2020-11-22 17:46

    For a regular dict, you can use:

    mydict[k_new] = mydict.pop(k_old)
    

    This will move the item to the end of the dict, unless k_new was already existing in which case it will overwrite the value in-place.

    For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2 to 'two':

    >>> d = {0:0, 1:1, 2:2, 3:3}
    >>> {"two" if k == 2 else k:v for k,v in d.items()}
    {0: 0, 1: 1, 'two': 2, 3: 3}
    

    The same is true for an OrderedDict, where you can't use dict comprehension syntax, but you can use a generator expression:

    OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())
    

    Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.

提交回复
热议问题