gpt4 book ai didi

python - 如何确保 python 字典键是小写的?

转载 作者:太空狗 更新时间:2023-10-29 19:30:27 24 4
gpt4 key购买 nike

我有一个字典,我想使用 simplejson 将其转换为 JSON。

如何确保我的字典的所有键都是小写的?

    {
"DISTANCE": 17.059918745802999,
"name": "Foo Bar",
"Restaurant": {
"name": "Foo Bar",
"full_address": {
"country": "France",
"street": "Foo Bar",
"zip_code": "68190",
"city": "UNGERSHEIM"
},
"phone": "+33.389624300",
"longitude": "7.3064454",
"latitude": "47.8769091",
"id": "538"
},
"price": "",
"composition": "",
"profils": {},
"type_menu": "",
"ID": ""
},

编辑:感谢大家看了我的问题,很抱歉我没有详细解释为什么我想要这个。它是为 django-pistonJSONEmitter 打补丁。

最佳答案

>>> d = {"your": "DATA", "FROM": "above"}
>>> dict((k.lower(), v) for k, v in d.iteritems())
{'from': 'above', 'your': 'DATA'}
>>> def lower_keys(x):
... if isinstance(x, list):
... return [lower_keys(v) for v in x]
... elif isinstance(x, dict):
... return dict((k.lower(), lower_keys(v)) for k, v in x.iteritems())
... else:
... return x
...
>>> lower_keys({"NESTED": {"ANSWER": 42}})
{'nested': {'answer': 42}}

关于python - 如何确保 python 字典键是小写的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4223654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com