gpt4 book ai didi

python - 将python字符串转换为字典

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:50 27 4
gpt4 key购买 nike

我有一个包含一行的 excel 文档,类似于:

{MGY: {1: 85, 2: 15}}
{MGY: {1:85, 2:15}, MWH: {1:99, 2:1}, MDE: {1:60, 2:40}, MIN: {1:60, 2:40}}
{MGY: {1:85, 2:15}}
{MWH: {1:99, 2:1}}
{MGY: {1:85, 2:15}}

当我尝试使用以下代码将行转换为字典时:

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> meta = {u'CODE': u'N03', u'FABRIC': u'Jersey', u'Colour mix': u'{MGY: {1: 85, 2: 15}}', u'WEIGHT G': 165, u'Main': u'3:100', u'WEIGHT OZ': 4}
>>> colour_mix = meta['Colour mix']
>>> colour_mix
u'{MGY: {1: 85, 2: 15}}'
>>> import ast
>>> melange_items = ast.literal_eval(colour_mix)

我得到以下回溯:

Traceback (most recent call last):
File "styles_fabric.py", line 194, in <module>
styleMeta = fabric_composition(style)
File "styles_fabric.py", line 185, in fabric_composition
melange_items = ast.literal_eval(dd)
File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.7/ast.py", line 63, in _convert
in zip(node.keys, node.values))
File "/usr/lib/python2.7/ast.py", line 62, in <genexpr>
return dict((_convert(k), _convert(v)) for k, v
File "/usr/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string

提取、转换字典中字符串的正确方法是什么?

最佳答案

我想你是想把 key 用引号引起来:

import ast
ast.literal_eval('{"MGY": {1: 85, 2: 15}}') # {'MGY': {1: 85, 2: 15}}

ast.literal_eval 可以 解析字符串文字,但 MGY 本身对它没有任何意义。

关于python - 将python字符串转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28027662/

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