Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python 3.x - Why I can not extract data from this dictionary though a loop?

I'm extracting from data which is of type dictionary.

import urllib3
import json

http = urllib3.PoolManager()
url = 'https://raw.githubusercontent.com/leanhdung1994/BigData/main/fr-esr-principaux-etablissements-enseignement-superieur.json'
f = http.request('GET', url)
data = json.loads(f.data.decode('utf-8'))

data[0]["geometry"]["coordinates"]

geo = []
n = len(data)
for i in range(n):
    geo.append(data[i]["geometry"]["coordinates"])

It returns an error

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-26-52e67ffdcaa6> in <module>
     12 n = len(data)
     13 for i in range(n):
---> 14     geo.append(data[i]["geometry"]["coordinates"])

KeyError: 'geometry'

This is weird, because, when I only run data[0]["geometry"]["coordinates"], it returns [7.000275, 43.58554] without error.

Could you please elaborate on this issue?


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

1 Reply

0 votes
by (71.8m points)

Error is occuring because in few of the response dictionaries you don't habe "geometry" key. Check before appending to geo list, that "geometry" key exists in response dict.

Try following code.

import urllib3
import json

http = urllib3.PoolManager()
url = 'https://raw.githubusercontent.com/leanhdung1994/BigData/main/fr-esr-principaux-etablissements-enseignement-superieur.json'
f = http.request('GET', url)
data = json.loads(f.data.decode('utf-8'))


geo = []
n = len(data)
for i in range(n):
    if "geometry" in data[i]:
        geo.append(data[i]["geometry"]["coordinates"])
print(geo)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...