gpt4 book ai didi

解析格式化字符串并从中获取字典的 Pythonic 方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:54:08 24 4
gpt4 key购买 nike

我有一个看起来像这样的字符串:

{
"key A":[
["some val", "value a1"],
["some val", "value a2"],
....................
["some val", "value an"]
], "key B":[
["some val", "value b1"],
["some val", "value b2"],
...
], ...
, "key X":[
["some val", "value x1"],
["some val", "value x2"],
...
]
}

谁能告诉我在 python 中从字典中取出字典的正确方法是什么

{
"key A": ["val a1", "val a2", ..."val an"],
"key B": ["val b1", "val b2", ..."val bn"],
.....
"key X": ["val x1", "val x2", ..."val xn"],
}

我问这个是因为现在我唯一能想到的代码是一个非常脏的代码,有很多列表、拆分和替换,我很确定这是非常错误的方法:D。非常感谢。

最佳答案

您可以使用 ast.literal_eval 和字典理解:

from ast import literal_eval

mystr = """{
"key A":[
["some val", "value a1"],
["some val", "value a2"],
["some val", "value an"]
], "key B":[
["some val", "value b1"],
["some val", "value b2"],
], "key X":[
["some val", "value x1"],
["some val", "value x2"],
]
}"""

res = {k: list(list(zip(*v))[1]) for k, v in literal_eval(mystr).items()}

# {'key A': ['value a1', 'value a2', 'value an'],
# 'key B': ['value b1', 'value b2'],
# 'key X': ['value x1', 'value x2']}

关于解析格式化字符串并从中获取字典的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49756350/

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