python3.6获取字典的key_在Python 3.6中解析字典以检索键

在给定的Python字典列表中,要提取'category_id'的值,可以使用更简洁的方法。例如,通过直接访问字典元素或者列表推导式来提高效率。例如:`cat_id = [line['category_id'] for line in lines]` 或者 `for line in lines: cat_id.append(line['category_id'])`。
摘要由CSDN通过智能技术生成

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?

解决方案

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值