Python - how to get all the values of nested dictionaries as a single List[dict]?

Viewed 63

I'm trying to parse this list to get a single List[dict] containing the dicts with data for all metric types.

metrics_info = [
    {
        "metric_type1": [
            {
                "name": "m10",
                "score": "11"
            },
            {
                "name": "m20",
                "score": "790"
            }
        ]},
    {
        "metric_type2": [
            {
                "name": "m30",
                "score": "245"

            }
        ]}
]

For now I've created a method that allows to get a list of dicts for a specific metric type:

def parse_metrics(metrics_info: List[dict], metric_type: str) -> List[dict]:
    for item in metrics_info:
        if metric_type in item:
            return item[metric_type]

How can I get a List[dict] containing the inner dictionaries for all metric types?

The result should look like this:

[
            {
                "name": "m10",
                "score": "11"
            },
            {
                "name": "m20",
                "score": "790"
            },
            {
                "name": "m30",
                "score": "245"
            }
]
3 Answers

There may be a fancier way, but his should do the job:

meterics_info = [ ... ]
all_values = []
for d in metrics_info:
    all_values.extend(d.values())

So I made a small modification to monkut's answer. Theirs returns a list of lists. It looks like you looking for a flattened list. I have two ways of doing this one uses for loops while the other uses the functional methods in python.

all_values= [item for _list in map(lambda _dict: list(_dict.values())[0], metrics_info) for item in _list]

OR

all_values = []
for _dict in metrics_info:
    for value in list(_dict.values()):
        all_values.extend(value)

Both produce the same result that you are looking for. A flattened list.

Another way of doing it through List Comprehension:

b=[]
[b.append(y) for i in metrics_info  for x,y in i.items()]
print(b)
Related