Parsing a dictionary to retrieve a key in Python 3.6

限于喜欢 提交于 2019-12-23 04:48:28

问题


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

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?


回答1:


Just pick element from dictionary:

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

or

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



回答2:


If you assume that each entry of your dicts contains that category, you can do it faster this way :

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

For any entries that have no 'category_id' a 'None' will be saved to the list



来源:https://stackoverflow.com/questions/48104644/parsing-a-dictionary-to-retrieve-a-key-in-python-3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!