2

I have a list in the below format.

['111: {"id":"de80ca97","data":"test"}', '222: {"id":"8916a167","data":"touch"}', '333: {"id":"12966e98","data":"tap"}']

I need to remove the data column from above list / json and replace it with key value of the list.

I need to transform it to the below structure. Desired output:

[
    {
     "score":111,
     "id":"de80ca97"
    },
    {
     "score":222,
     "id":"8916a167"
    },
    {
     "score":333,
     "id":"12966e98"
    }
]

Any suggestions or ideas most welcome.

2
  • 2
    What have you tried, and where are you stuck? Commented Jun 22, 2020 at 5:26
  • 1
    Few ideas: for-loop, str.split, json.loads. Commented Jun 22, 2020 at 5:37

1 Answer 1

2

You can use a for loop or you can also use a list comprehension as follows:

>>> import json
>>> l = ['111: {"id":"de80ca97","data":"test"}', '222: {"id":"8916a167","data":"touch"}', '333: {"id":"12966e98","data":"tap"}']
>>> [{'score': int(e.split()[0][:-1]), 'id': json.loads(e.split()[1])['id']} for e in l]

If you prefer to use a for loop:

new_l = []
for e in l:
    key, json_str = e.split()
    new_l.append({'score': int(key[:-1]), 'id': json.loads(json_str)['id']})
Sign up to request clarification or add additional context in comments.

1 Comment

You can do that with a single split: key, json_str = e.split(':', 1). In one-liner that may require the walrus operator.

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.