2013-04-01 25 views
0

大家好我有一個獨特的問題。它是如何設置鍵值項目的數量作爲Python中的鍵值

在一個關鍵字:值字典中,如何獲取項目列表的len並讓len成爲關鍵字值?

D = {'Chicago Cubs': 1907, 1908, 'World Series Not Played in 1904': [1904], 
    'Boston Americans': 1903, 'Arizona Diamondbacks': 2001, 
    'Baltimore Orioles':1966, 1970, 1983} 


Chicago Cubs: 1907,1908 

team = key and number of times shown = value 

後計數

Chicago Cubs - 2 

的時間出現的項目數我需要的是:

Chicago Cubs: 2 

我所擁有的是:

D = {} 
for e in l: 
    if e[0] not in D: 
     D[e[0]] = [e[1]] 
    else: 
     D[e[0]].append(e[1]) 

for k, v in sorted(D.items(), key=lambda x: -len(x[1])): 
    max_team = ("%s - %s" % (k,len(v))) 
    print(max_team) 
return max_team 

我該怎麼辦?

回答

3

你的字典的語法似乎無效嘗試這樣的事情(請注意,所有值已經被包圍在一個數組語法):

D = {'Chicago Cubs': [1907, 1908], 'World Series Not Played in 1904': [1904], 'Boston Americans': [1903], 'Arizona Diamondbacks': [2001], 'Baltimore Orioles':[1966, 1970, 1983]} 

然後使用這樣的(因爲它是更有效,因爲在字典中,一旦它只能訪問項目。

newDict = {} 
for key, value in D.iteritems(): 
    newDict [key] = len(value) 
+1

第二部分可以與一個字典理解做太:'N = {鍵:LEN(值)爲鍵時,在D.iteritems()值}' – askewchan

+0

當我用'iteritems(我正在一個錯誤)'我該怎麼辦?我正在使用Python 3.3.0。 –

+0

@askewchan:dict comp僅在Python 2.7+中可用 – jdi

1

我不知道我理解你的問題,但是這給一試:

d = {} 
"""add some items to d""" 

for key in d.keys(): 
    d[key] = len(d[key]) 

print d 
相關問題