Python 如果Dict值为空
那么,如何在多目录中检查值是否为空 我尝试了以下链接,但没有工作Python 如果Dict值为空,python,dictionary,Python,Dictionary,那么,如何在多目录中检查值是否为空 我尝试了以下链接,但没有工作 空字典是假的。如果不是dic,只需使用 In [54]: User Out[54]: {0: {'uid': ' rpatil\n'}, 1: {}} In [55]: User[0] Out[55]: {'uid': ' rpatil\n'} In [56]: User[1] Out[56]: {} In [57]: if User[1] == '': ....: print 'Null' ....:
空字典是假的。如果不是dic,只需使用
In [54]: User
Out[54]: {0: {'uid': ' rpatil\n'}, 1: {}}
In [55]: User[0]
Out[55]: {'uid': ' rpatil\n'}
In [56]: User[1]
Out[56]: {}
In [57]: if User[1] == '':
....: print 'Null'
....:
In [58]:
所以,在你的代码中
>>> testDict = {}
>>> if not testDict:
print "Empty"
Empty
>>> t = {}
>>> t == None
False
>>> t == {}
True
空字典=={}
。您还可以测试它是否为空字典
>>> User = {0: {'uid': ' rpatil\n'}, 1: {}}
>>> if not User[1]:
print "NULL"
NULL
用你的代码
>>> testDict = {}
>>> if not testDict:
print "Empty"
Empty
>>> t = {}
>>> t == None
False
>>> t == {}
True
User[1]
不是None
-它的值是空的dict:
>>> User = {0: {'uid': ' rpatil\n'}, 1: {}}
>>> if User[1] == {}:
print "NULL"
NULL
您需要:
>>> User[1] == {}
True
如果用户[1]
是0
怎么办。你想只检查空的dict吗?我不建议这样做,因为还有很多其他的东西是假的。@Surkit kalla-我认为你的方式更像python,但我觉得我的方式更清晰。。。想法?@kindall:是的,嗯,这取决于OP想要什么。如果他澄清了这一点,我可能会发布其他东西。@RyPeck:是的,但正如kindall指出的,其他东西也可能是假的,因此,如果OP特别想测试一本空字典,那么他就必须接受你的答案。:)“Pythonic”并不总是我们应该努力的目标尽管如此,你的两个答案都是+1,因为我喜欢它们。