How to do one dict into list of multi dict? Python

Question:

I would like to convert from json data to key value format, how to do?

My data

data = { 
  "type": "student",
  "age": "17",
  "sex": "male",
}

Expected Output

[ 
  { "type": "student", "key": "age", "value": "17"  },
  { "type": "student", "key": "sex", "value": "male"  },
]
Asked By: T_Ner

||

Answers:

I’m not very familiar with json and there might be a function in the json package for this conversion, but this works for your data:

data = { 
  "type": "student",
  "age": "17",
  "sex": "male",
}

out = []

for key, value in data.items():
    d = {"type": data["type"]}
    if key != "type":
        d["key"] = key
        d["value"] = value
        out.append(d)
out

Out:

[{'type': 'student', 'key': 'age', 'value': '17'},
 {'type': 'student', 'key': 'sex', 'value': 'male'}]
Answered By: Timo

you could use a function to generalize your output in case your dictionary have more keys that you want to key as they are or add then to your list of key value pair

def transfrom(data, non_key_value: list, key_value: list):
    base = {key: val for key, val in data.items() if key in non_key_value}
    ouput = [{**base, **{"key": val, "value": data[val]}} for val in key_value]
    return ouput
transfrom(data, non_key_value=["type"], key_value=["age", "sex"])
>>>
[{'type': 'student', 'key': 'age', 'value': '17'},
 {'type': 'student', 'key': 'sex', 'value': 'male'}]
Answered By: Lucas M. Uriarte

Here’s a way to do it with the pop method and the | operator:

data = {"type": "student", "age": "17", "sex": "male"}
base = {"type": data.pop("type")}
output = [base | {"key": key, "value": value} for key, value in data.items()]
print(output)

Output:

[{'type': 'student', 'key': 'age', 'value': '17'}, {'type': 'student', 'key': 'sex', 'value': 'male'}]

This code uses the pop method to remove the key from the dictionary and return it, which means that "base" becomes {"data": "student"} and "data" becomes {"age": "17", "sex": "male"}.

It then uses a list comprehension iterating over the remaining keys and values in "data", using the | operator to combine them with the key/value pair in "base" each time to create a new dictionary.

Note: the | operator was introduced in Python 3.9.

Answered By: Jack Taylor
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.