Reputation: 885
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 !
Upvotes: 1
Views: 326
Reputation: 123491
If the json-like file really has valid json on every line (your example doesn't quite), you could do something like the following (in Python 2 or 3):
import json
with open('json-like.txt') as data_file:
objs = (json.loads(line).popitem() for line in data_file)
data = {key: value['score'] for key, value in objs}
print(data) # -> {'Yet_another_one_': '5.7', 'Another_one': '9.8', 'Some_key': '3.46'}
Upvotes: 1
Reputation: 132078
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'}
Upvotes: 5