Hi,
I have a thousands of IP addresses, repeating randomly in my database and I wish to print each IP address along with the number of times they are repeated.

For example,
162.10.2.1
162.10.2.1
162.10.2.1
192.34.1.10
172.11.2.9
192.34.1.10
192.34.1.10

Output:
162.10.2.1 - 3
192.34.1.10 - 3
172.11.2.9 - 1

I have used Counter() to do this manually by listing them individually and then using Counter(list). As there are thousands of IP addresses, it is impossible to list them out manually in the program. Is there any way where I can get the output with a for loop or anything else?

Recommended Answers

All 6 Replies

Counter() is a dictionary,then you can iterate over it with a for loop.

>>> l = ['162.10.2.1', '162.10.2.1', '162.10.2.1', '192.34.1.10', '172.11.2.9']
>>> l
['162.10.2.1', '162.10.2.1', '162.10.2.1', '192.34.1.10', '172.11.2.9']
>>> from collections import Counter
>>> d = Counter(l)
>>> d
Counter({'162.10.2.1': 3, '172.11.2.9': 1, '192.34.1.10': 1})
>>> for k,v in sorted(d.iteritems()):
...     print '%s - %s' % (k,v)
...     
162.10.2.1 - 3
172.11.2.9 - 1
192.34.1.10 - 1
>>>

I seem to run Python v2.6 that does not support the Counter()feature. Is there any way in which I can do this without using Counter(). That is, can I count the IP addresses manually using some kind of a logic?

OK

For 2.6 you can do it like this.

>>> l = ['162.10.2.1', '162.10.2.1', '162.10.2.1', '192.34.1.10', '172.11.2.9']
>>> d = {}
>>> for v in l: d[v] = d.get(v, 0) + 1
... 
>>> d
{'162.10.2.1': 3, '172.11.2.9': 1, '192.34.1.10': 1}
>>> for k,v in sorted(d.iteritems()):
...     print '%s - %s' % (k,v)
...     
162.10.2.1 - 3
172.11.2.9 - 1
192.34.1.10 - 1
>>>

For 2.6 you can do it like this.

>>> l = ['162.10.2.1', '162.10.2.1', '162.10.2.1', '192.34.1.10', '172.11.2.9']
>>> d = {}
>>> for v in l: d[v] = d.get(v, 0) + 1
... 
>>> d
{'162.10.2.1': 3, '172.11.2.9': 1, '192.34.1.10': 1}
>>> for k,v in sorted(d.iteritems()):
...     print '%s - %s' % (k,v)
...     
162.10.2.1 - 3
172.11.2.9 - 1
192.34.1.10 - 1
>>>

You can also use defaultdict

>>> from collections import defaultdict
>>> l = ['162.10.2.1', '162.10.2.1', '162.10.2.1', '192.34.1.10', '172.11.2.9']
>>> d = defaultdict(int)
>>> for v in l: d[v] += 1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.