从嵌套字典列表中检索值

时间:2021-07-13 16:40:34

标签: python-3.x list dictionary

我有这本字典,我只想在字典值的“type”=“sorter”时获取别名的相应值,如果没有排序器,则获取最大计数的值。

例如

输入

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"},
    ]
}

输出

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

我可以使用

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'])

有什么简单的方法吗?

1 个答案:

答案 0 :(得分:1)

试试:

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)

打印:

{'agg': 'So_so'}

编辑:搜索多个值:

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)

打印:

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