简体   繁体   English

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

[英]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.

相关问题 Python-如何为字典中的值设置最大数量? - Python- How do I set a max number for a value in a dictionary? 如何使用python从列表中获取字典,将列表条目作为键,并将列表中的项数作为值? - How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python? Python:如何匹配键,然后将键值对值的值与另一个字典中的值相乘? - Python: How do I match keys then multiply the values of a key-value pair value with values from another dictionary? 如何使用列表的元素来设置字典的键和值? - How do I use elements of list to set the key and value of dictionary? 如何创建字典外的列表,其名称与字典键相同,并且大小与该键的值相同? - How do I create lists out of dictionary, having same name as dictionary keys and same size as value of that key? 如何在 python 字典中拥有键、键值对和唯一键? - How to have key,key value pair and only keys in python dictionary? Python:如何从字典键中随机选择一个值? - Python: How do I randomly select a value from a dictionary key? 如何在Python中汇总字典并按键值排序 - How do I Sum Dictionary in Python and Sort by Key Value 如何在 Python 中按键检索字典值? - How do I retrieve a dictionary value by key in Python? 如何在python字典中附加键的值? - How do I append the value of a key in a python dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM