0

I am trying to store two run options in Json. My attempt is as below. Is this a sensible way to organise Json object? Also how can I read either of them into tuples? I tried tuple([(item['opt_one'],item['val_one']) for item in config['opts']]) but git a key error. Many thanks for your help.

"opts":[
    {
        "opt_one": "one_option",
        "val_one" : "value_one"
     },
     {
        "opt_two": "two_option",
        "val_two" : "value_two"
      }
      ]
0

2 Answers 2

1
# or it can be done in 1 line
print(tuple(map(lambda v: tuple(v.values()), J['opts']))) 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot. But how can I also read either one of them, for example only opt_two and val_two into a tuple?
opts is a list of dictionaries. Each dictionary has an index (starting at 0). Each dictionary has keys() or values() or both - items(). J['opts'][0] and J['opts'][1] are the 2 dictionaries.
1
import json

j = """
{"opts":[
    {
        "opt_one": "one_option",
        "val_one" : "value_one"
     },
     {
        "opt_two": "two_option",
        "val_two" : "value_two"
      }
    ]
}
"""
# note the braces around "opts"

J = json.loads(j) #turns it into a python object
print(J) #see!

# the long way to do it, but you can see the process
R = []
for item in J['opts']:
    r = []
    for v in item.values():
        r.append(v)
    R.append(tuple(r))

print(tuple(R)) # solution

Comments

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.