简体   繁体   中英

KeyError in python

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']

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})

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?

Why not use

mylist= ['CLOSED', 'PENDING_PAYMENT', 'COMPLETE', 'CLOSED', 'COMPLETE', 'COMPLETE', 'COMPLETE', 'PROCESSING', 'PENDING_PAYMENT', 'PENDING_PAYMENT']
mylist.count("CLOSED")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM