-4

I want to make a function that get a list, like:

['comp1', 'comp2', 'comp1', 'mycomp', 'mycomp'] 

And return a dictionary that the key's is the name of the computers and the values is how many times the same name\key's repeated in the list.

Like if the list get input:

["computer17", "computer6", "comp", "computer17"]

So the return is:

["computer17":"2",...]
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
HelloWorld
  • 33
  • 2

1 Answers1

4

The easiest to way to count the items in a list is using a Counter object (Counter is a child-class of the built in dictionary):

>>> from collections import Counter
>>> computers = ['computer17', 'computer6', 'comps', 'computer17']
>>> Counter(computers)
Counter({'computer17': 2, 'comps': 1, 'computer6': 1})

Excerpt from the docs:

class Counter(__builtin__.dict)

Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.

Tim
  • 41,901
  • 18
  • 127
  • 145
timgeb
  • 76,762
  • 20
  • 123
  • 145