列表中有多个字典,如何取字典中的值

列表中有多个字典,如何取字典中的值,如下面的列表中有3个字典:
list=[{‘pathname’: ‘nameone’, ‘num’: 1, ‘status’: ‘RUN’}, {‘pathname’: ‘nametwo’, ‘num’: 2, ‘status’: ‘RUN’}, {‘pathname’: ‘namethree’, ‘num’: 3, ‘status’: ‘RUN’}]
现在要取第2个字典中的num对应的值,值为2。
如果按照取列表中第二个字典,字典中的第二个值表示为:list[1][1] (注意,字典或列表的下标都是从0开始的)会有错误提示:

list=[{'pathname': 'nameone', 'num': 1, 'status': 'RUN'}, {'pathname': 'nametwo', 'num': 2, 'status': 'RUN'}, {'pathname': 'namethree', 'num': 3, 'status': 'RUN'}]
print(list[1][1])

在这里插入图片描述

Traceback (most recent call last):
  File "E:/testgui/testscript/testind/test.py", line 35, in <module>
    print(list[1][1])
KeyError: 1

Process finished with exit code 1

正确的表示应该是第二个字典中,取key对应的value值:

list=[{'pathname': 'nameone', 'num': 1, 'status': 'RUN'}, {'pathname': 'nametwo', 'num': 2, 'status': 'RUN'}, {'pathname': 'namethree', 'num': 3, 'status': 'RUN'}]
print(list[1]['num'])

输出结果
在这里插入图片描述
如果需要取所有字典的num值,需要增加循环。代码如下:

list=[{'pathname': 'nameone', 'num': 1, 'status': 'RUN'}, {'pathname': 'nametwo', 'num': 2, 'status': 'RUN'}, {'pathname': 'namethree', 'num': 3, 'status': 'RUN'}]
for table in list:
    print(table['num'])

结果截图:
在这里插入图片描述

  • 12
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值