Madhu
Madhu

Reputation: 429

Retrieve values from list of nested dictionary

I have this dictionary, I want to get correesponding value of alias only if "type"="sorter" of dictionary values, if there is no sorter then get the value of maximum count.

for ex.

input

dct = {
    "agg": [
        {"count": 7, "type": "Aggregator", "alias": "Ag_ag"},
        {"count": 2, "type": "Sorter", "alias": "So_so"},
    ], 
 "fil": [
        {"count": 7, "type": "Filter", "alias": "fi_fu"},
        {"count": 2, "type": "Aggregator", "alias": "ag_so"},
        {"count": 2, "type": "expression", "alias": "ex_ex"},
    ]
}

output

{'agg':'So_so','fil':'fi_fu'}

I can achieve using

data_struct={
    "agg": [
        {"count": 7, "type": "Aggregator", "alias": "Ag_ag"},
        {"count": 2, "type": "Sorter", "alias": "So_so"},
    ], 
 "fil": [
        {"count": 7, "type": "Filter", "alias": "fi_fu"},
        {"count": 2, "type": "Aggregator", "alias": "ag_so"},
        {"count": 2, "type": "expression", "alias": "ex_ex"},
    ]
}

for key,value in data_struct.items():
        for v in value:
            #print(v)
            if v.get("type")== 'Sorter':
                rownum_dict[key] =v.get("alias")
                pass

# to get max

max_item = max(value, key=lambda x: x['count'])

is there any simple way for this?

Upvotes: 1

Views: 26

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195408

Try:

dct = {
    "agg": [
        {"count": 7, "type": "Aggregator", "alias": "Ag_ag"},
        {"count": 2, "type": "Sorter", "alias": "So_so"},
    ]
}

out = {"agg": next(d["alias"] for d in dct["agg"] if d["type"] == "Sorter")}
print(out)

Prints:

{'agg': 'So_so'}

EDIT: To search multiple values:

dct = {
    "agg": [
        {"count": 7, "type": "Aggregator", "alias": "Ag_ag"},
        {"count": 2, "type": "Sorter", "alias": "So_so"},
    ],
    "fil": [
        {"count": 7, "type": "Filter", "alias": "fi_fu"},
        {"count": 2, "type": "Aggregator", "alias": "ag_so"},
        {"count": 2, "type": "expression", "alias": "ex_ex"},
    ],
}


out = {
    k: max(
        (float("inf") if d["type"] == "Sorter" else d["count"], d["alias"])
        for d in v
    )[1]
    for k, v in dct.items()
}
print(out)

Prints:

{'agg': 'So_so', 'fil': 'fi_fu'}

Upvotes: 1

Related Questions