如何更改Python字典中条目的键?
当前回答
我在下面写了这个函数,您可以将当前键名的名称更改为新名称。
def change_dictionary_key_name(dict_object, old_name, new_name):
'''
[PARAMETERS]:
dict_object (dict): The object of the dictionary to perform the change
old_name (string): The original name of the key to be changed
new_name (string): The new name of the key
[RETURNS]:
final_obj: The dictionary with the updated key names
Take the dictionary and convert its keys to a list.
Update the list with the new value and then convert the list of the new keys to
a new dictionary
'''
keys_list = list(dict_object.keys())
for i in range(len(keys_list)):
if (keys_list[i] == old_name):
keys_list[i] = new_name
final_obj = dict(zip(keys_list, list(dict_object.values())))
return final_obj
假设一个JSON,你可以调用它,并通过以下行重命名它:
data = json.load(json_file)
for item in data:
item = change_dictionary_key_name(item, old_key_name, new_key_name)
在这里可以找到从列表到字典键的转换:https://www.geeksforgeeks.org/python-ways-to-change-keys-in-dictionary/
其他回答
因为键是字典用来查找值的,所以实际上不能更改它们。您可以做的最接近的事情是保存与旧键相关联的值,删除它,然后使用替换键和保存的值添加一个新条目。其他几个答案说明了实现这一目标的不同方式。
用下划线替换字典键中的空格,我使用这个简单的路由…
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()的信息
上面循环的一行代码是什么?
如果你想更改所有的键:
d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}
In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}
如果你想改变单键: 你可以选择上面的任何一个建议。
对于熊猫,你可以有这样的东西,
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'}
我在下面写了这个函数,您可以将当前键名的名称更改为新名称。
def change_dictionary_key_name(dict_object, old_name, new_name):
'''
[PARAMETERS]:
dict_object (dict): The object of the dictionary to perform the change
old_name (string): The original name of the key to be changed
new_name (string): The new name of the key
[RETURNS]:
final_obj: The dictionary with the updated key names
Take the dictionary and convert its keys to a list.
Update the list with the new value and then convert the list of the new keys to
a new dictionary
'''
keys_list = list(dict_object.keys())
for i in range(len(keys_list)):
if (keys_list[i] == old_name):
keys_list[i] = new_name
final_obj = dict(zip(keys_list, list(dict_object.values())))
return final_obj
假设一个JSON,你可以调用它,并通过以下行重命名它:
data = json.load(json_file)
for item in data:
item = change_dictionary_key_name(item, old_key_name, new_key_name)
在这里可以找到从列表到字典键的转换:https://www.geeksforgeeks.org/python-ways-to-change-keys-in-dictionary/
推荐文章
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构