使用dict理解时如何避免丢失键的错误 [英] How to avoid error on missing keys when using dict comprehension
问题描述
如何忽略pd.DataFrame.from_dict
理解迭代中的缺失键?
How do I ignore missing keys in a pd.DataFrame.from_dict
comprehension iteration?
@jezrael在此回答了我用字典值制作df的问题:
@jezrael kindly answered my problem on making a df with dictionary values here:
https://stackoverflow.com/a/49072184/9242601
但是我遇到了Key Error: 'fees'
错误,因为不是所有的"Customers"都有一个"fees"键,所以我希望迭代不只是产生一个错误,而是继续到下一个Customer,而不是记录该客户在df中.
But I encountered a Key Error: 'fees'
error because not all "Customers" have a 'fees' key, so rather than generating an error, I'd like the iteration to just move on to the next Customer and not record that customer in the df.
我仍然需要一个数据框,因此try... except
和if key in dict
将不起作用,因为我最终将得到一个空的(或不存在的)df.
I still need a dataframe, so try... except
and if key in dict
won't work, because I will just end up with an empty (or non-existent) df.
将这个问题有效地推广到两个问题的歉意,但我认为不值得重复完整的初始问题(因此链接).
Apologies for effectively spreading this question over two questions, but I didn't think it was worth repeating the complete initial question (hence the link).
谢谢.
推荐答案
链接没问题-它在Stackoverflow中,没有任何作用.
The link's OK - it's in Stackoverflow and isn't going anywhere.
满足dict.get
方法.通过序言,这几乎是您需要了解的所有内容:
Meet the dict.get
method. By way of a pre-amble, this is almost everything you need to know about it:
>>> d = {'present': 'real_value'}
>>> d.get('present')
'real_value'
>>> d.get('absent') is None
True
>>> d.get('absent', 'default')
'default'
您应该发现修改后的理解力
You should find that the modified comprehension
{k: dict(v['fees']) for k, v in d.items() if v.get('fees') is not None}
满足您的需求,但这是未经测试的代码.
serves your needs, but this is untested code.
这篇关于使用dict理解时如何避免丢失键的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!