0

大家好,我有一个独特的问题。

在 key:value 字典中,如何获取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

我该怎么办?

4

2 回答 2

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)
于 2013-04-01T21:56:35.397 回答
1

我不确定我是否理解您的问题,但请尝试一下:

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

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

print d
于 2013-04-01T21:52:55.053 回答