存在值时发生Keyerror

时间:2019-07-11 21:32:47

标签: python python-3.x

我正在尝试将列表转换为字典,同时提取列表中的一个元素并将其分配为ley,将另一个元素分配为值。列表看起来像

todos = [{"general":{"imgUrl":"https://media.licdn.com/dms/image/C5603AQEj3RU2C8iLyA/profile-displayphoto-shrink_800_800/0?e=1568246400&v=beta&t=TBI7KQkcTxdx8Cwbe9PQnP3dkbEc9SI1lLsRGYylS8g","fullName":"A. Valerie Mirko","headline":"General Counsel at North American Securities Administrators Association (NASAA)","company":"North American Securities Administrators Association (NASAA)","school":"The George Washington University Law School","location":"Washington, District Of Columbia","connections":"500+ connections","profileUrl":"https://www.linkedin.com/in/a-valerie-mirko-b856b510/","connectionDegree":"3rd","vmid":"ACoAAAI9K1UBjo3KEOpu_YEN3edB_0UdyvmHOb0","linkedinSalesNavigatorUrl":"https://www.linkedin.com/sales/people/ACoAAAI9K1UBjo3KEOpu_YEN3edB_0UdyvmHOb0,name","description":"","firstName":"A.","lastName":"Valerie Mirko"},"jobs":[{"companyName":"North American Securities Administrators Association (NASAA)","companyUrl":"https://www.linkedin.com/company/75855/","jobTitle":"General Counsel","dateRange":"Oct 2015 – Present","location":"Washington, DC","description":null},{"companyName":"North American Securities Administrators Association (NASAA)","companyUrl":"https://www.linkedin.com/company/75855/","jobTitle":"Legal Department (see below for positions)","dateRange":"Apr 2012 – Oct

我试图将列表的每个元素读入for循环,并将列表元素读入字典键和值。

Ldict={}
for i in todos:
    Ldict[i["general"]["fullName"]] = i['jobs']

我希望Ldict的fullName作为键,而Jobs作为值,这样我就可以将其转换为数据框,然后最终导出为ex​​cel。但是我得到的错误是

KeyError                                  Traceback (most recent call last)
<ipython-input-5-95e00e78255f> in <module>
      1 Ldict={}
      2 for i in todos:
----> 3     Ldict[i["general"]["fullName"]] = i['jobs']

KeyError: 'general'

虽然列表中存在“通用”。实际上

print(todos[0]['general']['fullName'])

将我的输出显示为

A. Valerie Mirko

1 个答案:

答案 0 :(得分:0)

请检查以确保整个列表中的每一个项目都具有“常规”属性。

如果该值存在,则不会抛出KeyError