如何判断dict中的列表是否为空

时间:2014-12-24 01:16:41

标签: python

我有movietimes={}

这是我用这段代码制作的一本词:

for i in Showtime.objects.filter(movie_id=movieid,theater_id=theaterid,datetime__range=(today,tomorrow))):
    if i.mvtype not in movietimes:
        movietimes[i.mvtype] = []
    if not i.movietime > today :
        movietimes[i.mvtype].append(i.movietime.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))

if not movietimes : #this have bug
    for i in Showtime.objects.filter(movie_id=movieid,datetime__range=(yesterday,today)):
        if i.mvtype not in movietimes:
            movietimes[i.mvtype] = []
        movietimes[i.mvtype].append(i.movietime.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
return movietimes

结果如下:

     "Times": {
                "ONE: [
                    "2014-12-24T10:40:00.000000Z", 
                    "2014-12-24T12:45:00.000000Z", 
                    "2014-12-25T14:50:00.000000Z"
                ]
            }

我想问一下,如果“ONE”部分中的[]为空,我怎么能判断?

我无法使用if not movietimes={}:,因为dict中有u'ONE': []

我必须判断dict中的第一个列表是空的。并且有许多类型u'ONE',u'TWO',u'Three'

他们被i.mvtype

抓住了
{u'ONE': []}
{u'TWO': []}
{u'Three': []}

请帮助我,谢谢

1 个答案:

答案 0 :(得分:1)

if not movietimes["Times"]["ONE"]:
    # you have empty list

首先,假设你的意思是密钥ONE,因为这些密钥不是有序的

如果你想查看是否有空列表,你的字典如下:

movietimes = {"Times":{"ONE":[2],"TWO":[]}}

for val in movietimes["Times"].itervalues():
   if not any(x for x in val):
        # you have empty list