确定导致KeyError

时间:2017-10-26 01:05:16

标签: python pandas series keyerror try-except

我有一个大约58,000行的列表,每行都是一个字典。

示例:

my_list_of_dicts = 
[{'id': '555', 'lang': 'en'}, 
{'id': '444', 'lang': 'en'}, 
{'id': '333', 'lang': 'fr'},
{'id': '222', 'lang': 'es'}, 
{'id': '111', 'lang': 'ge'},
{'id': '666', 'lang': 'fr'}, 
{'id': '777', : 'du'}]

在每个字典中,你会看到我有一个带有相应值的“lang”键,这是几种语言的缩写('en','es','fr','du','ge '等等......)

我已成功编写了生成一个系列所需的代码,该系列包含此键中所有唯一值的value_count。

然而,当我这样做时,我得到一个KeyError,因为显然有一些字典不包含'lang'值。

我创建了一个try / except命令,允许我跳过这些缺失的值。看起来58,000中有5行,缺少'lang'键。

我想找到'lang'这些缺失值的位置。换句话说,在大约58,000行中,如何找到哪5行缺少'lang'键?

4 个答案:

答案 0 :(得分:1)

您可以使用getenumerate

my_list_of_dicts = 
[{'id': '555', 'lang': 'en'}, 
 {'id': '444', 'lang': 'en'}, 
 {'id': '333', 'lang': 'fr'},
 {'id': '222', 'lang': 'es'}, 
 {'id': '111', 'lang': 'ge'},
 {'id': '666', 'lang': 'fr'}, 
 {'id': '777', "missing_lang": 'du'}]
 missing_vals = [i for i, a in enumerate(my_list_of_dicts) if not a.get("lang", False)]

请记住,您包含: 'du'的原始词典是一个无效的键值对,这会在您运行文件时引发错误。因此,我为演示目的添加了一个占位符值。

答案 1 :(得分:0)

在评论中取消上述答案,

 counter = 0:
 for item in my_list_of dicts:
      if "lang" not in item:
           print(counter)
      counter += 1

获取ID密钥,

for item in my_list_of_dicts:
      if "lang" not in item:
           print(item['id'])

答案 2 :(得分:0)

你的列表不是真实的例子,因为dict中没有键。 我们假设看起来像这样: <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://use.fontawesome.com/a0aac8df13.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/js/bootstrap.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="2000"> <div class="carousel-inner row w-100 mx-auto" role="listbox"> <div class="carousel-item col-md-6 active"> <blockquote class="blockquote"> <p>Attendees Rated The Program An Overwhelming Success. Your Tools, Techniques And Thought Provoking Ideas On Leadership, Communication Skills And Attitude Left Folks Wanting More.</p> <footer class="blockquote-footer"><cite>Vickie Doyle, Vice President, Membership<br> Tucson Convention & Visitors Bureau</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote"> <p>Since Our Seminar, Our Management Team Has Taken More Responsibility In Working With All New Hires.</p> <footer class="blockquote-footer"><cite>Dominic R. Palmiers, CEO<br> Odyssey Foods, LLC</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote text-center"> <p>&quot;Our Most Concise Training To Date!</p> <footer class="blockquote-footer"><cite>John Comeau<br> Mohegan Sun Casino</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote"> <p>Several Commented On How Mr. Scott Conveyed A Sense of Understanding And Genuine Desire To Provide Them With Concrete And Realistic Answers To The Questions And Concerns.</p> <footer class="blockquote-footer"><cite>Maria Meza, Training & Development Manager<br> Tohono O'odham Gaming Authority</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote"> <p>It Was One Of The Best Trainings I've Ever Seen. Our Gaming Board Attended A Session And Just Loved It!</p> <footer class="blockquote-footer"><cite>Marcus Diaz, Director of Training<br> Casino Del Sol</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote"> <p>Your Customer Service Training On November 11, 2003, Was One Of The Best Training Events I Have Ever Experienced!</p> <footer class="blockquote-footer"><cite>Robert Taschetta, Help Desk Manager<br> Best Western International</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote"> <p>The Feedback That I Received From The Employees Was Overwhelming...The Information You Passed On & Taught Them Was Invaluable. I Have Seen Many Of The Golden Eagle Distributors Employees Use A Wide Variety Of The Techniques That You Taught On A Daily Basis & People Are Thinking About Their Actions.</p> <footer class="blockquote-footer"><cite>Richard H. Wortman, Corporate Training Director<br> Golden Eagle Distributors</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote"> <p>In A Very Short Period of Time Our Level of Guest Service & Professionalism Has Dramatically Improved...You Built A Much Stronger And Confident Team.</p> <footer class="blockquote-footer"><cite>Lynn W. Smith, General Manager<br> Smuggler's Inn</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote"> <p>I Was Skeptical About This Experiential Training, But It Was Phenomenal!</p> <footer class="blockquote-footer"><cite>Ana Zysko, Director of Training<br> Inn Of The Mountain Gods Resort & Casino</cite></footer> </blockquote> </div> <div class="carousel-item col"> <blockquote class="blockquote"> <p>Peter Scott's Programs Are All About Content & Core Values.</p> <footer class="blockquote-footer"><cite>Dr. Thomas Dullien, Executive Director Human Resources & HR Development<br> Barona Resort & Casino</cite></footer> </blockquote> </div> </div> <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev"> <i style="color:#FF8C46; text-decoration: none;" class="fa fa-chevron-circle-left fa-2x"></i> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next"> <i style="color:#FF8C46; text-decoration: none;" class="fa fa-chevron-circle-right fa-2x"></i> <span class="sr-only">Next</span> </a> </div> </div> <div class="clearfix"></div>

您可以使用以下命令获取包含索引和项目的元组列表:

my_list_of_dicts = [ {'id': '555', 'lang': 'en'}, {'id': '444', 'lang': 'en'}, {'id': '777', 'x': 'du'}]

答案 3 :(得分:0)

由于此问题标记为pandas,您可以尝试使用DataFrame构造函数:

In [11]: my_list_of_dicts = \
    ...: [{'id': '555', 'lang': 'en'},
    ...: {'id': '444', 'lang': 'en'},
    ...: {'id': '333', 'lang': 'fr'},
    ...: {'id': '222', 'lang': 'es'},
    ...: {'id': '111', 'lang': 'ge'},
    ...: {'id': '666', 'lang': 'fr'},
    ...: {'id': '777', }]  # example one with no lang

In [12]: df1 = pd.DataFrame(my_list_of_dicts)

In [13]: df1
Out[13]:
    id lang
0  555   en
1  444   en
2  333   fr
3  222   es
4  111   ge
5  666   fr
6  777  NaN

In [14]: df1[df1.lang.isnull()]  # rows with a NaN (missing) lang
Out[14]:
    id lang
6  777  NaN