Home javascript android java php c# ubuntu python c++ c ios TAGS

KeyError in python


Date : 2019-08-16 18:44:57 , By : Aamir Ahmad Ansari

I am trying to count the number of times each string in my list is repeated but it keeps giving me KeyError:

def gono(l):
    f={}
    for h in l:
        if(f.get(f[h])):
            f[h] += 1
        else:
            f[h]=1
    return f
Error content :
KeyError                                  Traceback (most recent call last)
<ipython-input-68-e02904625299> in <module>
     23             f[h]=1
     24     return f
---> 25 v=gono(h)
     26 v
     27 

<ipython-input-68-e02904625299> in gono(l)
     18     f={}
     19     for h in l:
---> 20         if(f.get(f[h])):
     21             f[h] += 1
     22         else:

KeyError: 'CLOSED'

The list is : ['CLOSED', 'PENDING_PAYMENT', 'COMPLETE', 'CLOSED', 'COMPLETE', 'COMPLETE', 'COMPLETE', 'PROCESSING', 'PENDING_PAYMENT', 'PENDING_PAYMENT']

TAGS : python
Answers :
By : J.Smith

I think this question doesn't belong to "data science", this is more of a python coding question. Anyways it seems like dictionary is empty when you call the function first. How you can call f[h] without getting a key error in this case?

By : Peter

Why not use

mylist= ['CLOSED', 'PENDING_PAYMENT', 'COMPLETE', 'CLOSED', 'COMPLETE', 'COMPLETE', 'COMPLETE', 'PROCESSING', 'PENDING_PAYMENT', 'PENDING_PAYMENT']
mylist.count("CLOSED")
By : 0x5453

Just use a Counter:

from collections import Counter
def gono(l):
    return Counter(l)

Example result:

>>> gono(['CLOSED', 'PENDING_PAYMENT', 'COMPLETE', 'CLOSED', 'COMPLETE', 'COMPLETE', 'COMPLETE', 'PROCESSING', 'PENDING_PAYMENT', 'PENDING_PAYMENT'])
Counter({'COMPLETE': 4, 'PENDING_PAYMENT': 3, 'CLOSED': 2, 'PROCESSING': 1})
- Technology - Yellow pages
» java
» php
» c#
» ubuntu
» python
» c++
» c
» ios
» jquery
» html
» sql
» r
» mysql
» linux
» access
» iphone
» css
» excel
» vb.net
» .net
» ruby
Privacy Policy - Copyrights Notice - Terms - Contact Us 2019 © tinytut
Licensed under cc by-sa 3.0 with attribution required.