如何更改Python字典中条目的键?
当前回答
这个函数获得一个字典,另一个字典指定如何重命名键;它返回一个新的字典,带有重命名的键:
def rekey(inp_dict, keys_replace):
return {keys_replace.get(k, k): v for k, v in inp_dict.items()}
测试:
def test_rekey():
assert rekey({'a': 1, "b": 2, "c": 3}, {"b": "beta"}) == {'a': 1, "beta": 2, "c": 3}
其他回答
您可以将相同的值与许多键相关联,或者只是删除一个键并重新添加具有相同值的新键。
例如,如果你有键->值:
red->1
blue->2
green->4
没有理由不能添加紫色->2或删除红色->1并添加橙色->1
这将小写你所有的字典键。即使你有嵌套的字典或列表。您可以执行类似的操作来应用其他转换。
def lowercase_keys(obj):
if isinstance(obj, dict):
obj = {key.lower(): value for key, value in obj.items()}
for key, value in obj.items():
if isinstance(value, list):
for idx, item in enumerate(value):
value[idx] = lowercase_keys(item)
obj[key] = lowercase_keys(value)
return obj
json_str = {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}], "EMB_DICT": {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}]}}
lowercase_keys(json_str)
Out[0]: {'foo': 'BAR',
'bar': 123,
'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}],
'emb_dict': {'foo': 'BAR',
'bar': 123,
'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}]}}
对于熊猫,你可以有这样的东西,
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'}
完整解决方案的示例
声明一个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
我在下面写了这个函数,您可以将当前键名的名称更改为新名称。
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/
推荐文章
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 不区分大小写的字符串作为HashMap键
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- 使用linq转换列表到字典,不用担心重复
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本