在Python 3.6中解析字典以检索密钥

在Python 3.6中解析字典以检索密钥,python,dictionary,python-3.6,Python,Dictionary,Python 3.6,我有一本Python字典,我正试图找出如何获取特定的键和值 这里是示例Python字典,我需要检索category\u id值 lines = [ {'id': 'sub_BUNbsaTbxzrZYW', 'category_id': 'prodcat_xMOTFxgQnA', 'object': 'line_item', 'amount': 9999, 'currency': 'usd', 'description': '1x Yearly (at $99.99)', 'discounta

我有一本Python字典,我正试图找出如何获取特定的键和值

这里是示例Python字典,我需要检索
category\u id

lines = [ 
 {'id': 'sub_BUNbsaTbxzrZYW', 'category_id': 'prodcat_xMOTFxgQnA', 'object': 'line_item', 'amount': 9999, 'currency': 'usd', 'description': '1x Yearly (at $99.99)', 'discountable': True, 'livemode': True, 'metadata': {}, 'period': {'start': 1538833681, 'end': 1570369681}, 'plan': {'id': 'Nuts Yearly', 'object': 'plan', 'amount': 10000, 'created': 1498624603, 'currency': 'usd', 'interval': 'year', 'interval_count': 1, 'livemode': False, 'metadata': {}, 'name': 'Nuts Yearly', 'statement_descriptor': None, 'trial_period_days': None}, 'proration': False, 'quantity': 1, 'subscription': None, 'subscription_item': 'si_1B7OqTAQofPy1JZrjB5myHN5', 'type': 'subscription'}, 


 {'id': 'sub_BUNbsaTbxzrZYW', 'category_id': 'prodcat_jbWGPxLNHM', 'object': 'line_item', 'amount': 9999, 'currency': 'usd', 'description': '1x Yearly (at $99.99)', 'discountable': True, 'livemode': True, 'metadata': {}, 'period': {'start': 1538833681, 'end': 1570369681}, 'plan': {'id': 'Nuts Yearly', 'object': 'plan', 'amount': 10000, 'created': 1498624603, 'currency': 'usd', 'interval': 'year', 'interval_count': 1, 'livemode': False, 'metadata': {}, 'name': 'Nuts Yearly', 'statement_descriptor': None, 'trial_period_days': None}, 'proration': False, 'quantity': 1, 'subscription': None, 'subscription_item': 'si_1B7OqTAQofPy1JZrjB5myHN5', 'type': 'subscription'}], 'has_more': False, 'object': 'list', 'url': '/v1/invoices/in_1Bg1FZAQofPy1JZrLNlHERmz/lines'}] 
我可以通过以下方式获取数据:

cat_id = []
for i in lines:
    for k, v in i.items():
        if k == 'category_id':
            cat_id.append(v)

如何使我的代码在这种情况下更有效?

如果您假设您的DICT的每个条目都包含该类别,则可以通过以下方式更快地完成:

cat_id = []
for i in lines:
    cat_id.append(i.get("category_id"))

对于没有“category\u id”的任何条目,“None”将保存到列表中

只需从字典中选择元素:

cat_id = []
for line in lines:
    cat_id.append(line['category_id'])


你不是只想要
[line['category\u id']作为行中的行]
(搜索“列表理解”)?在字典上进行迭代似乎没有任何意义,通过键进行有效的查找正是他们优化的目的。此外,这不是解析,而且您有一个字典列表。您的代码不工作吗?看起来应该能用。可能需要一些优化,但这就是CodeReview stackexchange的用途。@jonrsharpe谢谢!这是一个更干净:)我甚至可以添加一个条件,使列表只有当它匹配一个特定的id时才被创建。感谢您的帮助。另外,感谢您对措辞的澄清。@HubertGrzeskowiak代码确实有效。谢谢你让我知道CodeReview。
cat_id = [line['category_id'] for line in lines]