I have a string that looks like this:
{
"key A":[
["some val", "value a1"],
["some val", "value a2"],
....................
["some val", "value an"]
], "key B":[
["some val", "value b1"],
["some val", "value b2"],
...
], ...
, "key X":[
["some val", "value x1"],
["some val", "value x2"],
...
]
}
Can anyone tell me what is the proper way in python to get a dictionary out of it where the dictionary should be
{
"key A": ["val a1", "val a2", ..."val an"],
"key B": ["val b1", "val b2", ..."val bn"],
.....
"key X": ["val x1", "val x2", ..."val xn"],
}
I'm asking this because right now the only code I can think of is a pretty dirty one with a lot of list, splits and replaces and I'm quite sure that this is very wrong way to do it :D. Thanks a lot in advance.
You can use ast.literal_eval with a dictionary comprehension:
from ast import literal_eval
mystr = """{
"key A":[
["some val", "value a1"],
["some val", "value a2"],
["some val", "value an"]
], "key B":[
["some val", "value b1"],
["some val", "value b2"],
], "key X":[
["some val", "value x1"],
["some val", "value x2"],
]
}"""
res = {k: list(list(zip(*v))[1]) for k, v in literal_eval(mystr).items()}
# {'key A': ['value a1', 'value a2', 'value an'],
# 'key B': ['value b1', 'value b2'],
# 'key X': ['value x1', 'value x2']}
As eval is generally regarded as unsafe and python dictionaries are "usually" JSON compatible, as long as all values are also JSON compatible. I would recommend:
import json
mystr = """{
"key A":[
["some val", "value a1"],
["some val", "value a2"],
["some val", "value an"]
], "key B":[
["some val", "value b1"],
["some val", "value b2"]
], "key X":[
["some val", "value x1"],
["some val", "value x2"]
]
}"""
res = json.loads(mystr)
for dealing with trailing commas:
import json
from jsoncomment import JsonComment
mystr = """{
"key A":[
["some val", "value a1"],
["some val", "value a2"],
["some val", "value an"]
], "key B":[
["some val", "value b1"],
["some val", "value b2"],
], "key X":[
["some val", "value x1"],
["some val", "value x2"],
]
}"""
res = JsonComment(json).loads(mystr)
docs for JsonComment: https://pypi.python.org/pypi/jsoncomment
ref: Can json.loads ignore trailing commas?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With