0

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?

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?

Thomas Jones
  • 355
  • 2
  • 11
  • 17

2 Answers2

3

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)
Juan Carlos Moreno
  • 2,754
  • 3
  • 22
  • 21
  • 1
    The second part can be done with a dict comprehension too: `N = { key:len(value) for key,value in D.iteritems() }` – askewchan Apr 01 '13 at 22:06
  • I am getting an error when I use `iteritems()` what should I do? I'm using python 3.3.0. – Thomas Jones Apr 01 '13 at 22:09
  • @askewchan: dict comp is only available in python 2.7+ – jdi Apr 01 '13 at 22:16
  • 1
    @ThomasJones: In py3 they were made generators by default [http://wiki.python.org/moin/Python3.0] - "Remove dict.iteritems(), dict.iterkeys(), and dict.itervalues(). Instead: use dict.items(), dict.keys(), and dict.values() respectively." – jdi Apr 01 '13 at 22:19
1

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
Ionut Hulub
  • 6,180
  • 5
  • 26
  • 55