0

I would like to make three different lists out of a JSON file (https://www.dropbox.com/s/woxtqy634g89f0r/tags.json?dl=0) say, A, B, and C:

A: (13,13,...,37)
B: (12,14,...,32)
C: ([-1.3875, 1.3875, -1.95 ], [[-2.775, -0., -0., ], .., [-0., 2.775, -0. ]])

Is there any quick and smart way to do it?

I tried in jupyter-notebook:

with open('tags.json', 'r') as f:
    tags = json.load(f)
tags['neb.00']

the output would give me

'13->12 0.2906332796567428 [-1.3875 1.3875 -1.95 ]'

And then I can do something like tags['neb.03'][0:2] to get 13 and so on. But this is not a good way of doing and I hope there is a proper way to do it. Could anyone help me, please?

1
  • "this is not a good way of doing" Why not? Commented Sep 26, 2019 at 19:29

2 Answers 2

2
for k,v in data.items():
    A =v[:v.index('-')]
    B =v[v.index('>')+1:v.index('[')]
    C =v[v.index('[')::]
    print(k,A,B,C)

.items() iterates through dict keys(k) and values(v)

i don't know if that's the answer you were looking for but looking at your data, it seems like it has a stable structure. i guess you can append each value to a list.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks @FMARAD. That's exactly I was looking for. It solved my problem!
Hi, actually I realized there is a tiny bit of thing still left. If you look at 'C' in the main question, it's actually a list but what I am getting is a string obvioisuly like [-1.3875 1.3875 -1.95 ] but I want [-1.3875, 1.3875, -1.95 ]. Could you please help me with that?
C.strip("[]").split(",")
Somehow that didn't work for me. It only changed from [-1.3875 1.3875 -1.95 ] to ['-1.3875 1.3875 -1.95 '].
so i just got on my PC, C. strip("[]").split() but this would give you list of strings, i guess you can manipulate that.
|
0
import json
import re

with open('tags.json', 'r') as f:
    tags = json.load(f)

A = []
B = []
C = []
for x in sorted(tags.keys()):
    m = re.search(r'(\d+)->(\d+) (\d+\.\d+) \[(.+)\]', tags[x])
    if not m:
        print("Not matching:", tags[x])
        continue
    A.append(int(m.group(1)))
    B.append(int(m.group(2)))
    C.append([float(y) for y in m.group(4).split()])

sorted() or other functions if you need your items ordered in a deterministic way.

2 Comments

Didn't work for me. Giving me: AttributeError: 'NoneType' object has no attribute 'group'
That means the regex did not match. Your input is probably more complex than the example you posted. Edited to skip non-matching pattern so that you can refine the regex.

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.