如何使用Python小写json dict中的所有键

问题描述 投票:0回答:2

我是这个网站的新手,所以请对我温柔,没有同伴。

我目前正在使用代码来练习我的Python技能,这些代码将对照JSON字典检查给定的键并为您提供键的定义。现在,我知道我的问题还有其他解决方案,但是我正在尝试找出可能的解决方案。

我正在尝试将字典中的所有键更改为小写,并且现在我正尝试这样操作:

data = json.load(open("data.json"))

for key in data.keys():
    key = key.lower()

此字典文件的外观(一个键的示例:):

"act": ["Something done voluntarily by a person, and of such a nature that certain legal consequences attach to it.", "Legal documents, decrees, edicts, laws, judgments, etc.", "To do something.", "To perform a theatrical role."]

显然,每个键有多个值,在尝试其他解决方案时会产生问题。

python json dictionary lowercase
2个回答
1
投票

您可以尝试这个,

data = json.load(open("data.json"))
new_data = {key.lower():value for key, value in data.items()}

然后您可以用新数据替换旧数据。

with open("data.json") as fp:
    json.dump(new_data, fp)

1
投票

@ bumblebee提供的解决方案是正确且最小的。但是,如果您难以理解字典理解,请参考以下代码(我与@bumblebee的代码不同)


data = json.load(open("data.json"))
new_data = {}
for key, value in data.items():
    new_data[key.lower()] = value

# any code if you want to add further

with open("data.json") as fp:
    json.dump(new_data, fp)

© www.soinside.com 2019 - 2024. All rights reserved.