首页 > 解决方案 > Python:当字典具有错误值时,“NoneType”对象没有属性“键”

问题描述

我正在尝试使用 json_normalize 将嵌套字典转换为 DataFrame。我能够成功地做到这一点,直到我忽略了一些结果的错误。

长话短说 - 我在 python 中使用 Youtube-dl 来抓取一个 youtube 频道,然后我将结果数据转换为 DF。每当 youtube 视频出现错误时,我都会在 youtube-dl 中忽略它并继续下一个。我认为这是创建一个错误的字典条目,导致我的 json_normalize 失败。

这是我获取频道数据的方式

!pip install --upgrade youtube-dl
import youtube_dl 
import pandas as pd
import json


church = input('enter the name of the church')
method = 'y'
channelID = input('enter channel url ending in videos')


with youtube_dl.YoutubeDL({'ignoreerrors' : True}) as ydl:
  result = ydl.extract_info(
    str(channelID),
    download=False,
  )

result然后我使用以下代码段转换为 DF

import json



data = pd.json_normalize(
  result, 
  record_path =['entries'],
  errors='ignore'
)

但是,由于某些视频由于 youtube 错误而被跳过,所以每次运行 json_normalize 函数时都会出现以下错误

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-101-e3aa31b503f3> in <module>()
     19   result,
     20   record_path =['entries'],
---> 21   errors='ignore'
     22 )

4 frames
pandas/_libs/lib.pyx in pandas._libs.lib.fast_unique_multiple_list_gen()

/usr/local/lib/python3.7/dist-packages/pandas/core/internals/construction.py in <genexpr>(.0)
    635     """
    636     if columns is None:
--> 637         gen = (list(x.keys()) for x in data)
    638         sort = not any(isinstance(d, dict) for d in data)
    639         columns = lib.fast_unique_multiple_list_gen(gen, sort=sort)

AttributeError: 'NoneType' object has no attribute 'keys'

有人可以建议我需要做些什么来解释那些糟糕的字典条目吗?

标签: pythonjsondictionary

解决方案


您能否不使用以下内容预先筛选您的数据列表:

data = [x for x in data if x is not None]

推荐阅读