您现在的位置是:网站首页> 编程资料编程资料

如何利用python实现列表嵌套字典取值_python_

2023-05-26 295人已围观

简介 如何利用python实现列表嵌套字典取值_python_

一、实例

将以下列表的backup_unit_id全部提取出来

示例:

dbs = [{         "backup_unit_id": 163,         "data_node_id": 2,         "attribute": {             "convertor_id": 4,             "channel_num": 2,             "sga": "90G"         }     },     {         "backup_unit_id": 164,         "data_node_id": 3,         "attribute": {             "convertor_id": 9,             "channel_num": 2,             "sga": "90G"         }     } ]

二、解决思路

1、确定需要取值的对象是什么类型(列表还是字典)
2、此处确定类型为列表,列表下嵌套了字典
3、所以取值的时候要用到列表取值,字典取值
4、先把列表的值提取出来,也就是通过for…in…进行遍历
5、列表的值提取返回结果为字典类型,所以进一步取值时,通过字典的key获取,例:i[“key”]

三、代码示例

代码如下(示例):

dbs = [{         "backup_unit_id": 163,         "data_node_id": 2,         "attribute": {             "convertor_id": 4,             "channel_num": 2,             "sga": "90G"         }     },     {         "backup_unit_id": 164,         "data_node_id": 3,         "attribute": {             "convertor_id": 9,             "channel_num": 2,             "sga": "90G"         }     } ] for i in dbs:     # print(i)     print(i["backup_unit_id"])

返回结果(示例):

163
164

到此这篇关于如何利用python实现列表嵌套字典取值的文章就介绍到这了,更多相关python字典取值内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网