如何更改Python字典中条目的键?
当前回答
方法,如果有人想替换多级字典中出现的所有键。
函数检查字典是否有特定的键,然后遍历子字典并递归调用该函数:
def update_keys(old_key,new_key,d):
if isinstance(d,dict):
if old_key in d:
d[new_key] = d[old_key]
del d[old_key]
for key in d:
updateKey(old_key,new_key,d[key])
update_keys('old','new',dictionary)
其他回答
只需2步即可轻松完成:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
或者一步:
dictionary[new_key] = dictionary.pop(old_key)
如果字典[old_key]未定义,将引发KeyError。注意,这将删除字典[old_key]。
>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1
您可以将相同的值与许多键相关联,或者只是删除一个键并重新添加具有相同值的新键。
例如,如果你有键->值:
red->1
blue->2
green->4
没有理由不能添加紫色->2或删除红色->1并添加橙色->1
完整解决方案的示例
声明一个json文件,其中包含你想要的映射
{
"old_key_name": "new_key_name",
"old_key_name_2": "new_key_name_2",
}
加载它
with open("<filepath>") as json_file:
format_dict = json.load(json_file)
创建此函数来使用映射格式化字典
def format_output(dict_to_format,format_dict):
for row in dict_to_format:
if row in format_dict.keys() and row != format_dict[row]:
dict_to_format[format_dict[row]] = dict_to_format.pop(row)
return dict_to_format
对于熊猫,你可以有这样的东西,
from pandas import DataFrame
df = DataFrame([{"fruit":"apple", "colour":"red"}])
df.rename(columns = {'fruit':'fruit_name'}, inplace = True)
df.to_dict('records')[0]
>>> {'fruit_name': 'apple', 'colour': 'red'}
用下划线替换字典键中的空格,我使用这个简单的路由…
for k in dictionary.copy():
if ' ' in k:
dictionary[ k.replace(' ', '_') ] = dictionary.pop(k, 'e r r')
或者只是dictionary。pop(k)注意'e r r',它可以是任何字符串,如果键不在字典中,就会成为新的值,从而能够替换它,这在这里不可能发生。参数是可选的,在其他类似的代码中,KeyError可能会被击中,添加的arg会避免它,但可以创建一个新的键'e rr '或任何你设置的值。
.copy()避免…字典在迭代过程中改变了大小。
.keys()不需要,k是每个键,k在我的头脑中代表键。
(我使用v3.7)
关于字典pop()的信息
上面循环的一行代码是什么?
推荐文章
- 不区分大小写的字符串作为HashMap键
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- 使用linq转换列表到字典,不用担心重复
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架