在Python 3.6中解析字典以检索键 [英] Parsing a dictionary to retrieve a key in Python 3.6

查看:97
本文介绍了在Python 3.6中解析字典以检索键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python字典,我想弄清楚如何获取特定的键和值.

I have a Python dictionary and I am trying to figure out how to get a specific key and value.

这是示例Python词典,我需要检索category_id值.

Here is the example Python dictionary and I need to retrieve the category_id value.

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

我可以使用以下方式获取数据:

I am able to get the data using:

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

如何在这种情况下提高代码效率?

How can I make my code more efficient for this scenario?

推荐答案

只需从字典中选择元素:

Just pick element from dictionary:

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

cat_id = [line['category_id'] for line in lines]

这篇关于在Python 3.6中解析字典以检索键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆