如何提取列表中字典的指定key值并赋值给单独的变量
实现代码
首先建议不要使用list作为变量名,这是Python内置类型名,覆盖后会引发未知问题,修改后完整示例如下:
# 原始返回结果(修改了变量名避免冲突) file_info_list = [{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}] # 取出列表中第一个字典元素 file_item = file_info_list[0] # 赋值到对应变量 file_type = file_item['file_type'] access = file_item['access_time'] modification = file_item['modification_time'] blocksize = file_item['blocksize'] path = file_item['path']
注:示例中的数值末尾的
L是Python2的长整型标识,Python3环境下会自动识别为普通整数,无需额外处理。
如果需要避免key不存在时报错,可以改用get方法取值,无对应key时会返回None而非抛出异常:
access = file_item.get('access_time') modification = file_item.get('modification_time')
如果返回列表包含多个文件的信息,用循环批量处理即可:
for item in file_info_list: access = item['access_time'] modification = item['modification_time'] # 后续对应处理逻辑
内容的提问来源于stack exchange,提问作者Eduardo
相关产品推荐
相关产品推荐

