繁体   English   中英

我如何将key:value字典中的项数设置为python中的键值

[英]How do it I set the number of items in a key:value dictionary as the keys value in python

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

在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

我应该怎么做?

您的字典语法似乎无效,请尝试以下操作(注意,所有值都包含在数组语法中):

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)

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

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

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

print d

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM