Rename a dictionary key

后端 未结 12 829
盖世英雄少女心
盖世英雄少女心 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:50

    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}

提交回复
热议问题