-1

I am new to python, I am interested in to count repeated keys of dictionary in this case dates. I have this peace of code since in operator checks membership of keys its only checking once of the repeated keys.

import datetime
from collections import defaultdict

amount = 0
d = {'12-Aug-2018' : 22 ,
    '11-Aug-2018' :  5,
    '10-Aug-2018' : 3,
    '10-Aug-2018' : 2,
    '9-Aug-2018' : 1,
    '9-Aug-2018' : 6
    }

dcount = defaultdict(lambda:0)

for date in d:
       dcount[date] +=1
       print (d[date])

print(dcount.items())

Output:

22
5
2
6
dict_items([('12-Aug-2018', 1), ('11-Aug-2018', 1), ('10-Aug-2018', 1), ('9-Aug-2018', 1)])

value 3 of the key 10-Aug-2018 and value 1 of 9-Aug-2018' are skipped.

Desired output:

([('12-Aug-2018', 1), ('11-Aug-2018', 1), ('10-Aug-2018', 2), ('9-Aug-2018', 2)])

Any help? Thanks

Daniel
  • 42,087
  • 4
  • 55
  • 81
Hayat Khan
  • 111
  • 1
  • 4

2 Answers2

0

There are no duplicate keys in the dictionaries, your code is not real:

>>> d = {'12-Aug-2018' : 22 ,
...     '11-Aug-2018' :  5,
...     '10-Aug-2018' : 3,
...     '10-Aug-2018' : 2,
...     '9-Aug-2018' : 1,
...     '9-Aug-2018' : 6
...     }
>>> d
{'10-Aug-2018': 2, '9-Aug-2018': 6, '12-Aug-2018': 22, '11-Aug-2018': 5}
lenik
  • 23,228
  • 4
  • 34
  • 43
  • '10-Aug-2018' is two times similarly '9-Aug-2018' is also two times. My code is real and i think there is some misunderstanding. – Hayat Khan Aug 12 '18 at 16:20
  • @HayatKhan when you put them into the dictionary, duplicates are gone. – lenik Aug 12 '18 at 16:21
-5

You can use collections.Counter:

Python 2.7.15 (default, May 16 2018, 17:50:09) 
[GCC 8.1.1 20180502 (Red Hat 8.1.1-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import Counter
>>> dates = ('12-Aug-2018', '11-Aug-2018', '10-Aug-2018', '10-Aug-2018', '9-Aug-2018', '9-Aug-2018')
>>> Counter(dates)
Counter({'10-Aug-2018': 2, '9-Aug-2018': 2, '12-Aug-2018': 1, '11-Aug-2018': 1})
>>> 
accdias
  • 5,160
  • 3
  • 19
  • 31
  • the OP is using a dict, not a tuple. – Daniel Aug 12 '18 at 16:21
  • 1
    It was just to give OP an example on how to use ```Counter```. – accdias Aug 12 '18 at 21:39
  • And ```Counter``` will work with Dictionaries as well (as with any other iterable). – accdias Aug 12 '18 at 21:49
  • `Counter` is as good as the `defaultdict` the OP uses, but does not address his problem. – Daniel Aug 13 '18 at 07:33
  • Why not? If used the right way, it will address the problem without much effort. Obviously it doesn't address the wrong usage of a dict with duplicated keys, as showed in the example posted by the OP, but he can do something like ```c = Counter()``` and then ```c.update({'10-Aug-2018': 3})``` followed by ```c.update({'10-Aug-2018': 2})``` and so on for every keypair. ```Counter()``` will update the values for each key accordingly. – accdias Aug 13 '18 at 13:55