Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-Regex将最后一个键/值匹配到字典字符串中_Python_Regex_Dictionary - Fatal编程技术网

Python-Regex将最后一个键/值匹配到字典字符串中

Python-Regex将最后一个键/值匹配到字典字符串中,python,regex,dictionary,Python,Regex,Dictionary,我以字符串形式从文件中读取此词典: string = '{"key1":"value1", "key2":"value2"}' 我不知道key1和key2可以假定哪些值,我需要访问写入字符串的最后一对的值(在本例中为“value2”)。因此,将其转换为python字典是不可能的,因为它可能会改变顺序 我试过这样的方法: value = re.search(r'"(.*?)":"(.*?)"', string) 但是我不知道如何访问最后一场比赛的.group(2)。您可以这样做: import

我以字符串形式从文件中读取此词典:

string = '{"key1":"value1", "key2":"value2"}'
我不知道key1和key2可以假定哪些值,我需要访问写入字符串的最后一对的值(在本例中为“value2”)。因此,将其转换为python字典是不可能的,因为它可能会改变顺序

我试过这样的方法:

value = re.search(r'"(.*?)":"(.*?)"', string)
但是我不知道如何访问最后一场比赛的.group(2)。

您可以这样做:

import re
output = re.findall(".*\"[a-zA-Z0-9]+\"[\w]*:[\w]*\"(.+)\"[\w]*}", string)
输出:

>>> re.findall(".*\"[a-zA-Z0-9]+\"[\w]*:[\w]*\"(.+)\"[\w]*}", string)
['value2']

你就不能试试
eval()
?。为什么订单很重要?为什么这些数据不以列表的形式出现呢?请看我标记为dupe的问题的公认答案,我认为这比regexp更明智。