7

I have a dictionary of lists for which I want to add a value to a particular list... I have the following dictionary of lists.

d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill' 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}

I want to essentially count out the number of names and return in. So in this case it would be something like

Adam: 2
Bill: 2
John: 1
Bob: 1
Joe: 1

To make things easier, all names are the second element in the list or

for i in d:
     d[i][1]

Any idea how I can do this efficiently? I'm currently just manually checking for each name and counting and returning that =/

Thanks in advance!

user1530318
  • 25,507
  • 15
  • 37
  • 48
  • What happens if it is not only in the 1 position, so if it has to be accessed by i[x] where x is some position where the element is located? values[x] doesnt seem to work if you traverse through all of d.itervalues – user1530318 Aug 01 '12 at 23:38

2 Answers2

17

collections.Counter is always good for counting things.

>>> from collections import Counter
>>> d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}
>>> # create a list of only the values you want to count,
>>> # and pass to Counter()
>>> c = Counter([values[1] for values in d.itervalues()])
>>> c
Counter({'Adam': 2, 'Bill': 2, 'Bob': 1, 'John': 1, 'Joe': 1})
monkut
  • 42,176
  • 24
  • 124
  • 155
1
d = {'key': 'value'}
temp_dict = {}
for key, values in d.items():
    if values[1] in temp_dict:
        temp_dict[values[1]] = temp_dict[values[1]] + 1
    else:
        temp_dict[values[1]] = 1

This code is longer than the previous answer, but it's just another way to produce the same results. Anyway, temp_dict will store the names as keys and values as the number of times it shows up.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
Bob
  • 11
  • 2