【问题标题】:How to lowercase all keys in json dict with Python如何使用 Python 小写​​ json dict 中的所有键
【发布时间】:2020-05-26 04:27:26
【问题描述】:

我是这个网站的新手,所以对我温柔一点,不是同性恋。

我目前正在使用代码来练习我的 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."]

显然,每个键都有一个以上的值,这在尝试其他解决方案时会产生问题。

【问题讨论】:

  • key = key.lower() 只是将新的小写 str 对象分配给局部变量 key

标签: python json dictionary lowercase


【解决方案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)

【讨论】:

  • 谢谢,这解决了我的问题!我已经尝试过按照您的说明制作 new_data 变量,但它不能正常工作,这是我正在使用的:new_data = dict((key.lower(), value) for key, value in data.keys() )。我猜那里有问题,但感谢您展示正确的方法!
  • @AdiKešetović 这不起作用,因为您试图仅获取键而不是提供键值对的项目。那应该是: new_data = dict((key.lower(), value) for key, value in a.items())
  • @srahul07 我试过你的解决方案,它也有效!感谢您解释错误,现在它是有道理的。
【解决方案2】:

@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)

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 1970-01-01
    • 2017-08-19
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多