Reputation: 1
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?
Upvotes: 0
Views: 103
Reputation: 4323
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]
Upvotes: 1
Reputation: 16526
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
Upvotes: 0