【发布时间】:2020-09-02 18:10:26
【问题描述】:
我需要使用键 'name' 搜索列表字典并返回第一个匹配项的字典。例如,使用 'name' 搜索 'Sales' 并返回 dict 项。
second_step = [{'node': {'id': 'QWNjb3VudDo5NDI1MjA4NDI1NDAxMDgwMTQ7QnVzaW5lc3M6MGRmZDM5ODAtNzQ3OS00ZGQ4LTg5NWYtMzU4ZWNiNDNmMTI2', 'name': 'Commodity Credit Loans', 'description': 'Income received from a Commodity Credit Corporation as part of a farm price and income support commodity program.', 'displayId': None, 'type': {'name': 'Income', 'value': 'INCOME'}, 'subtype': {'name': 'Income', 'value': 'INCOME'}, 'normalBalanceType': 'CREDIT', 'isArchived': False}}, {'node': {'id': 'QWNjb3VudDo5NDI1MjA4NDI2MjM5OTQwOTg7QnVzaW5lc3M6MGRmZDM5ODAtNzQ3OS00ZGQ4LTg5NWYtMzU4ZWNiNDNmMTI2', 'name': 'Sales', 'description': 'Payments from your customers for products and services that your business sold.', 'displayId': None, 'type': {'name': 'Income', 'value': 'INCOME'}, 'subtype': {'name': 'Income', 'value': 'INCOME'}, 'normalBalanceType': 'CREDIT', 'isArchived': False}}, {'node': {'id': 'QWNjb3VudDo5NDI1MjA4NDI1ODIwNTEwNTY7QnVzaW5lc3M6MGRmZDM5ODAtNzQ3OS00ZGQ4LTg5NWYtMzU4ZWNiNDNmMTI2', 'name': 'Services', 'description': 'Income received from professional services rendered to your customers.', 'displayId': None, 'type': {'name': 'Income', 'value': 'INCOME'}, 'subtype': {'name': 'Income', 'value': 'INCOME'}, 'normalBalanceType': 'CREDIT', 'isArchived': False}}]
我这样做了:
next((item for item in second_step if item["name"] == "Sales"), None)
我收到了这个错误:
Traceback (most recent call last):
File "<pyshell#429>", line 1, in <module>
next((item for item in second_step if item["name"] == "Sales"), None)
File "<pyshell#429>", line 1, in <genexpr>
next((item for item in second_step if item["name"] == "Sales"), None)
KeyError: 'name'
我希望以下内容作为结果返回。
{'id': 'QWNjb3VudDo5NDI1MjA4NDI2MjM5OTQwOTg7QnVzaW5lc3M6MGRmZDM5ODAtNzQ3OS00ZGQ4LTg5NWYtMzU4ZWNiNDNmMTI2', 'name': 'Sales', 'description': 'Payments from your customers for products and services that your business sold.', 'displayId': None, 'type': {'name': 'Income', 'value': 'INCOME'}, 'subtype': {'name': 'Income', 'value': 'INCOME'}, 'normalBalanceType': 'CREDIT', 'isArchived': False}
我错过了什么?
【问题讨论】:
标签: python dictionary