如果给定的键和值与字典列表中的匹配,则获取所有字典

2024-06-17 19:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如果键和值的给定值匹配,我想从dict列表中获取dict。下面是我的输入和预期输出。你知道吗

输入:

[
    {
        "sqlFile": "test.sql",
        "noOfStatements": 3,
        "allQueries": "queries",
        "sqlOperations": [
            {
                "type": "CreateTable",
                "objectName": "objectname1",
                "schemaName": null
            },
            {
                "type": "CreateTable",
                "objectName": "objectname2",
                "schemaName": null
            },
            {
                "type": "DROP",
                "objectName": "objectname3",
                "schemaName": null
            }
        ]
    }
]

预期产量:

[
            {
                "type": "CreateTable",
                "objectName": "objectname1",
                "schemaName": null
            },
            {
                "type": "CreateTable",
                "objectName": "objectname2",
                "schemaName": null
            }
]

json\u数据有响应,sql\u操作有上面指定的输入。下面的代码没有按预期工作。我需要帮助确定问题以获得预期的结果。你知道吗

for i in json_data:
        logger.debug("I is :: {} ".format(type(i)))
        sql_operations = i['sqlOperations']
        for j in sql_operations:
            logger.debug("J is :: {} ".format(type(j)))
            for k,v in j.items():
                if k == 'operationType' and v == 'REPLACE View':
                     logger.debug("Key is {} and Item is {}".format(k,v))

Tags: indebugformatforsqlistypelogger
3条回答

作为一个单一的列表,你可以做

output = [d for i in json_data for d in i['sqlOperations'] if d['type'] == 'CreateTable']

或使用循环的标准

output = []
for i in json_data:
    for d in i['sqlOperations']:
        if d['type'] == 'CreateTable':
            output.append(d)
x = """ [{
    "sqlFile":
    "test.sql",
    "noOfStatements":
    3,
    "allQueries":
    "queries",
    "sqlOperations": [{
        "type": "CreateTable",
        "objectName": "objectname1",
        "schemaName": null
    }, {
        "type": "CreateTable",
        "objectName": "objectname2",
        "schemaName": null
    }, {
        "type": "DROP",
        "objectName": "objectname3",
        "schemaName": null
    }]
}]"""
import json
x = json.loads(x)
a = x[0]["sqlOperations"][0:2]
print(json.dumps(a, indent=2))

输出

[
  {
    "type": "CreateTable",
    "objectName": "objectname1",
    "schemaName": null
  },
  {
    "type": "CreateTable",
    "objectName": "objectname2",
    "schemaName": null
  }
]

假设您使用json.load以python dict列表的形式获取您的输入,那么您可以使用列表理解来实现这一点吗?你知道吗

for i in json_data:
    ops = i.get('sqlOperations', [])
    select_dicts = [d for d in ops if d.get('type') == 'CreateTable']
    new_list.extend(select_dicts)

new_list
[{'type': 'CreateTable', 'objectName': 'objectname1', 'schemaName': None}, 
{'type': 'CreateTable', 'objectName': 'objectname2', 'schemaName': None}]

相关问题 更多 >