简体   繁体   English

Python Re:使用正则表达式搜索列表

[英]Python Re: Searching through a list using regex

I am trying to search through a fairly complicated string that I am retrieving from a website. 我正在尝试搜索从网站检索的一个相当复杂的字符串。 This is a list of product ID's from a online store. 这是来自在线商店的产品ID的列表。 The string is as follows: 字符串如下:

['{ "40710": { "params": ["Black", "37"]}, "40711": { "params": ["Black", "37,5"]}, "40712": { "params": ["Black", "38"]}, "40713": { "params": ["Black", "38,5"]}, "40714": { "params": ["Black", "39"]}, "40715": { "params": ["Black", "40"]}, "40716": { "params": ["Black", "40,5"]}, "40717": { "params": ["Black", "41"]} }']

I am hoping to create a dictionary from this data by having the ID(the five digit numbers) as the key, and the size (the two-three digit numbers). 我希望通过以ID(五位数字)作为键和大小(两三位数字)从该数据创建字典。

This is what I want the dictionary to look like: 这就是我希望字典看起来像的样子:

dictionary = {'40710':'37', '40711':'37,5', '40712':'38', '40713':'38,5', '40714':'39', '40715':'40', '40716':'40,5', '40717':'41'}

I don't know if regex is the way to go with this, but everything seems to point to it; 我不知道正则表达式是否可以解决这个问题,但是似乎所有事情都指向它。 however, I really have no idea how to process data like this. 但是,我真的不知道如何处理这样的数据。 I could really use some help here. 我真的可以在这里使用一些帮助。

Thanks in advance. 提前致谢。

A dictionary comprehension after converting to a Python object with json.loads should do: 使用json.loads转换为Python对象后,对字典的理解应为:

import json

d = {k: v['params'][1] for k, v in json.loads(lst[0]).items()}
print(d)
# {'40710': '37', '40711': '37,5', '40712': '38', '40713': '38,5', '40714': '39', '40715': '40', '40716': '40,5', '40717': '41'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM