Amanda Amanda - 2 years ago 64
Python Question

parse json without explciitely calling the key-name

I have a json-like file with valid json per line that looks like

{"Some_key": {"name": "Tom", "school_code":"5678", "sport": "football", "score":"3.46", "classId": "456"}}
{"Another_one": {"name": "Helen", "school_code":"7657", "sport": ["swimming", "score":"9.8", "classId": "865"}}
{"Yet_another_one_": {"name": "Mikle", "school_code":"7655", "sport": "tennis", "score":"5.7", "classId": "76532"}}

So I need to create dictionary(? not really need the dictionary format but anything that could help me associate the key with value, array of two elements for ex) by extracting these first keys (i.e. "Some_Key", "Another_key" etc), that I don't know in advance, and then associating to them the value of score key inside the dictionary. so something like:

("Some_key":"3.46", "Another_Key":"9.8", "Yet_another_one_"; "5.7")

I don't know the method to extract the content without calling the key-name explicitly, so your ideas are more than welcome !

Answer Source

This works for Python2 and Python3

>>> {k: v.get('score') for item in data for k, v in item.items()}
{'Another_one': '9.8', 'Some_key': '3.46', 'Yet_another_one_': '5.7'}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download