Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

多个list dict嵌套 如何快速获取某个list

腾讯云CDN日志的数据格式为:
data={"Data": [{"Resource": "all", "DetailData": [{"Name": "cdn.asd.com/asd/asdfg.mp4", "Value": 2972209657}, {"Name": "cdn.asd.com/asd/hjkl.jpg", "Value": 12856187}]}], "RequestId": "asd-erf-ghj-qwe-zxc"}

如何快速获取其中的一个list:
[{"Name": "cdn.asd.com/asd/asdfg.mp4", "Value": 2972209657}, {"Name": "cdn.asd.com/asd/hjkl.jpg", "Value": 12856187}]

我有比较笨的办法,就是一级级拿:

get_Data=[v for k,v in data.items() if k=="Data"]

得到get_Data值:
[[{'Resource': 'all', 'DetailData': [{'Name': 'cdn.asd.com/asd/asdfg.mp4', 'Value': 2972209657}, {'Name': 'cdn.asd.com/asd/hjkl.jpg', 'Value': 12856187}]}]]

get_Data_dict=get_Data[0][0]

得到get_Data_dict值:
{'Resource': 'all', 'DetailData': [{'Name': 'cdn.asd.com/asd/asdfg.mp4', 'Value': 2972209657}, {'Name': 'cdn.asd.com/asd/hjkl.jpg', 'Value': 12856187}]}

get_DetailData=[v for k,v in get_Data_dict.items() if k=="DetailData"][0]

得到最终值:
[{'Name': 'cdn.asd.com/asd/asdfg.mp4', 'Value': 2972209657}, {'Name': 'cdn.asd.com/asd/hjkl.jpg', 'Value': 12856187}]

比较繁琐,有没有比较优雅的办法?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你的日志数据是结构化json数据,可以考虑使用json解析库, 比如ijson
假定json描述如下

{
  "earth": {
    "europe": [
      {"name": "Paris", "type": "city", "info": { ... }},
      {"name": "Thames", "type": "river", "info": { ... }},
      // ...
    ],
    "america": [
      {"name": "Texas", "type": "state", "info": { ... }},
      // ...
    ]
  }
}

获取 europe 列表 ,则用法这样

import ijson

f = urlopen('http://.../')
objects = ijson.items(f, 'earth.europe.item')
cities = (o for o in objects if o['type'] == 'city')
for city in cities:
    do_something_with(city)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...