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

来自:网络
时间:2022-08-04
阅读:
目录

一、实例

将以下列表的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

返回顶部
顶部