0

I create the following OrderedDict:

import collections

class obj1():
    def __init__(self):
          self.aa = 22
          self.bb = 23

class obj2():
    def __init__(self):
          self.dd = 22
          self.ee = 23

my_test = collections.OrderedDict()

my_test['1'] = obj1
my_test['2'] = obj1
my_test['3'] = obj1
my_test['4'] = obj2

and this is the outcome:

my_test
Out[41]: 
OrderedDict([('1', __main__.obj1),
             ('2', __main__.obj1),
             ('3', __main__.obj1),
             ('4', __main__.obj2)])

As it can be noticed, there are two types of object: obj1 and obj2. I would like to know if it is possible to know the number of obj1 (i.e. 3) in that OrderedDict structure.

I was thinking about a cycle over all the tuples. This approach has, however, two problems:

  1. I do not know how to extract the object name,
  2. it seems no so straightforward.
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
diedro
  • 511
  • 1
  • 3
  • 15

3 Answers3

1

You can use collections.Counter for this!

This will count all the instances, and give them as keys in a dict, mapping to their count in the iterator. Since Python type objects are hashable, this works.

With your previous example:

counts = collections.Counter(my_test.values())
print(counts[obj1])
>>> 3
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Egeau
  • 459
  • 1
  • 9
0

So you are looking for a way to count the occurrences of each class in the dictionary, right ?

occurrences = {}
for i in my_test:
  class_name = i.__class__.__name__
  occurrences[class_name] = occurrences.get(class_name, 0) + 1

That should give you a dictionary containing the classes as keys and their occurrences as values.

0

You can use another great class found in collections: Counter.

counts = collections.Counter(my_test.values())
print(counts)       # prints something like Counter({<class '__main__.obj1'>: 3, <class '__main__.obj2'>: 1})
print(counts[obj1]) # prints 3
Jasmijn
  • 9,370
  • 2
  • 29
  • 43