[英]How do it I set the number of items in a key:value dictionary as the keys value in python
Hello everyone I have an unique question. 大家好,我有一个独特的问题。
In a key:value dictionary, how do I get the len
of an item list and let the len
be the keys value? 在key:value字典中,如何获取项目列表的
len
,并让len
为键值?
Such as 如
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
After counting the number of times the item appears in 计算项目出现次数后
Chicago Cubs - 2
What I need is: 我需要的是:
Chicago Cubs: 2
What I have is: 我所拥有的是:
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
How should I go about this? 我应该怎么做?
Your dictionary's syntax seems invalid try something like this (notice that all values have been enclosed in an array syntax): 您的字典语法似乎无效,请尝试以下操作(注意,所有值都包含在数组语法中):
D = {'Chicago Cubs': [1907, 1908], 'World Series Not Played in 1904': [1904], 'Boston Americans': [1903], 'Arizona Diamondbacks': [2001], 'Baltimore Orioles':[1966, 1970, 1983]}
And then use something like this (as it is more efficient since it only access items in the dictionary once. 然后使用类似的方法(因为它只访问字典中的项目一次,所以效率更高。
newDict = {}
for key, value in D.iteritems():
newDict [key] = len(value)
I'm not sure I understood your question but give this a try: 我不确定我是否理解您的问题,但是可以尝试一下:
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.