David Schwartz
David Schwartz

Reputation: 45

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. 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).

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.

Upvotes: 0

Views: 86

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78554

A dictionary comprehension after converting to a Python object with json.loads should do:

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'}

Upvotes: 5

Related Questions