Pythonimport json
Create a dummy json file
data = [
{
"id": "4c111fbc-d13a-42b4-858c-1dc17fe3c1d1",
"name": "Grok-1",
"slug": "grok-1",
"release_date": "2024-03-17",
"model_creator": {
"id": "a1e3ddcf-d3e4-44a5-9e8f-029a69850875",
"name": "xAI",
"slug": "xai"
},
"evaluations": {
"artificial_analysis_intelligence_index": 18.2,
"artificial_analysis_coding_index": None,
"artificial_analysis_math_index": None,
"mmlu_pro": None,
"gpqa": None,
"hle": None,
"livecodebench": None,
"scicode": None,
"math_500": None,
"aime": None,
"aime_25": None,
"ifbench": None,
"lcr": None,
"terminalbench_hard": None,
"tau2": None
},
"pricing": {
"price_1m_blended_3_to_1": 0,
"price_1m_input_tokens": 0,
"price_1m_output_tokens": 0
},
"median_output_tokens_per_second": 0,
"median_time_to_first_token_seconds": 0,
"median_time_to_first_answer_token": 0
}
]
file_name = 'data.json'
with open(file_name, 'w') as f:
json.dump(data, f)
Read the file and convert to dict keyed by name
with open(file_name, 'r') as f:
data_list = json.load(f)
The transformation logic
models_dict = {item['name']: item for item in data_list}
Print result to verify
print(f"Keys in the dictionary: {list(models_dict.keys())}")
print(f"Accessing 'Grok-1': {models_dict['Grok-1']['id']}")
Code outputKeys in the dictionary: ['Grok-1']
Accessing 'Grok-1': 4c111fbc-d13a-42b4-858c-1dc17fe3c1d1
Here is the Python code to achieve this.Assuming your file is named data.json, this script reads the list and creates a new dictionary where each key is the name of the model.Pythonimport json
1. Open and load the JSON file
with open('data.json', 'r') as file:
data_list = json.load(file)
2. Convert the list into a dictionary keyed by "name"
This uses a dictionary comprehension to iterate through the list
models_dict = {item['name']: item for item in data_list}
--- Usage Examples ---
Check if the key exists and print the ID
if "Grok-1" in models_dict:
print(f"Found Grok-1 with ID: {models_dict['Grok-1']['id']}")
Print all keys
print(models_dict.keys())
Explanationjson.load(file): Parses the JSON file and converts it into a Python list of dictionaries.{item['name']: item for item in data_list}: This is a dictionary comprehension. It iterates over every element in the list (item) and sets the dictionary key to item['name'] and the value to the whole item object.Note: If your JSON list contains multiple elements with the same "name", this method will keep only the last one encountered, overwriting previous entries.