Python:从Python字典中删除空列表的一种优雅方法 [英] Python: An elegant way to delete empty lists from Python dictionary
问题描述
我有一个字典,如:
default = {'a': ['alpha'], 'b': ['beta','gamma'], 'g': []}
我希望消除以下空白值:
I wish to eliminate the empty values as:
default = {'a': ['alpha'], 'b': ['beta','gamma']}
我写了一个函数(下面是在网上找到的一个例子)
I wrote a function (following an example found on the web)
def remove_empty_keys(d):
for k in d.keys():
try:
if len(d[k]) < 1:
del[k]
except:
pass
return(d)
我有以下问题:
1-我没有找到错误,为什么它总是在以下情况下返回-
1- I didn't find the mistake why it always returns following -
remove_empty_keys(default)
{'a': ['alpha'], 'b': ['beta'], 'g': []}
2-是否有内置函数可以在不创建原始字典副本的情况下从Python字典中消除/删除Null/None/empty值?
2- Is there a built-in function to eliminate/delete Null/None/empty values from Python dictionary without creating a copy of the original dictionary?
推荐答案
要修复您的功能,请将del[k]
更改为del d[k]
.无法删除字典中的值.
To fix your function, change del[k]
to del d[k]
. There is no function to delete values in place from a dictionary.
您正在做的是删除变量k
,完全不更改字典.这就是为什么总是返回原始词典的原因.
What you are doing is deleting the variable k
, not changing the dictionary at all. This is why the original dictionary is always returned.
重写后,您的函数可能如下所示:
Rewritten, your function might look like:
def remove_empty_keys(d):
for k in d.keys():
if not d[k]:
del d[k]
这假定您要消除空列表和None
值,并实际上删除具有"false"值的任何项目.
This assumes you want to eliminate both empty list and None
values, and actually removes any item with a "false" value.
这篇关于Python:从Python字典中删除空列表的一种优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!