2014-12-24 39 views
0

我有一個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={}:,因爲u'ONE': []在字典

我有判斷在字典第一個列表是空的。而且有許多類型u'ONE 'u'TWO',u'Three」

他們漁獲i.mvtype

{u'ONE': []} 
{u'TWO': []} 
{u'Three': []} 

請幫幫我,謝謝

+0

人們或名單,不要判斷他們。 – thefourtheye

+0

...或者列表可能會判斷你返回 – smci

+1

等待,「dict中的第一個列表」是什麼意思?字典沒有訂購。 – senshin

回答

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 
+0

所以我必須輸入[「ONE」] ??它可以被代碼捕獲嗎?因爲我有很多[[一個]] [「兩個」] [「三個」] ... ... – user2492364

+1

你可以但它取決於你的字典是如何構造的 –

相關問題