Rename a dictionary key

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

    In Python 3.6 (onwards?) I would go for the following one-liner

    test = {'a': 1, 'old': 2, 'c': 3}
    old_k = 'old'
    new_k = 'new'
    new_v = 4  # optional
    
    print(dict((new_k, new_v) if k == old_k else (k, v) for k, v in test.items()))
    

    which produces

    {'a': 1, 'new': 4, 'c': 3}
    

    May be worth noting that without the print statement the ipython console/jupyter notebook present the dictionary in an order of their choosing...

提交回复
热议问题