重命名字典的键 [英] Renaming the keys of a dictionary

查看:80
本文介绍了重命名字典的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python字典中更改键?

How to change a key in a Python dictionary?

例程返回字典. 字典一切正常,只是需要重命名几个键.下面的代码将字典条目(key = value)复制到具有所需键的新条目中,然后删除旧条目.有没有一种更Python化的方法,也许不需要重复值?

A routine returns a dictionary. Everything is OK with the dictionary except a couple keys need to be renamed. This code below copies the dictionary entry (key=value) into a new entry with the desired key and then deletes the old entry. Is there a more Pythonic way, perhaps without duplicating the value?

my_dict = some_library.some_method(scan)
my_dict['qVec'] = my_dict['Q']
my_dict['rVec'] = my_dict['R']
del my_dict['Q'], my_dict['R']
return my_dict

推荐答案

dict键是不可变的.这意味着它们无法更改.您可以从文档

dict keys are immutable. That means that they cannot be changed. You can read more from the docs

字典由键编入索引,键可以是任何 不可变类型

dictionaries are indexed by keys, which can be any immutable type

这是使用 dict.pop

>>> d = {1:'a',2:'b'}
>>> d[3] = d.pop(1)
>>> d
{2: 'b', 3: 'a'}

这篇关于重命名字典的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆