如何将字符串解析成字典 [英] how to parse a string into a dictionary

查看:112
本文介绍了如何将字符串解析成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析一个字符串来分隔字符串中的列表。我现在有字符串:

I am trying to parse a string to separate the lists within the string. I currently have the string:

string = "[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]"

有什么方法来解析字符串,以便字典键是列表的第一个元素,键的值是元素的下一个。例如:

Is there any way to parse string so that the dictionary key is the first element of the list and the value of the key is the next to elements. For example:

{'q1': ('0','q1'), 'q1': ('1','q2'), 'q2': ('0','q2'), 'q2': ('1', 'q1')}


推荐答案

实现字典可以有列表:

您可以使用 ast.literal_eval 从字符串解析python数据结构

Insted of dictionary you can have list:
you can use ast.literal_eval to parse python data structure from string

>>> import ast
>>> my_string = "[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]"
>>> k = ast.literal_eval(my_string)
>>> k
[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]
>>> [[x[0],tuple(x[1:])] for x in k]
[['q1', ('0', 'q1')], ['q1', ('1', 'q2')], ['q2', ('0', 'q2')], ['q2', ('1', 'q1')]]

这篇关于如何将字符串解析成字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆