0

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.

1
  • 2
    have you tried json.loads() and then creating the dict you want from the parsed one? Commented Feb 28, 2017 at 18:11

1 Answer 1

5

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'}
Sign up to request clarification or add additional context in comments.

2 Comments

Um, so you changed the question so that your answer works?
Any chance you could provide an example on how to use json.loads to convert to a python object? I do not know anything about the JSON module in python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.