简体   繁体   中英

Python Error: TypeError: argument of type 'type' is not iterable

I'm learning to know how Python Dictionaries work and is writing a small program to know if the word awesome in the word count column, then it should return me the value.

However, it is giving me the following error:

TypeError: argument of type 'type' is not iterable

My word_count column is like below:

{'and': 5, 'stink': 1, 'because': 2}
{'awesome': 3, 'bad': 2}
{'mac': 5, 'awesome': 1}

I have created this function:

def awesome_count(self):
    if 'awesome' in dict:
        return dict['awesome']
    else:
        return 0

after then, I'm using apply function to get the count, but getting an error:

products['awesome'] = products['word_count'].apply(awesome_count)

Expecting the following answer:

0,3,1 i.e number of times awesome is present 

I am not sure if I got your idea, but I noted two things:

  1. You must indent the body of your function to mark the beginning and end of it. Python should give you an error if you type the way you did here.

  2. you called an apply method from the value products['soemthing'] that seems to me to be an integer value so it does not have a 'apply' method. The TypeError you receive tells you to call apply in an iterable object such as a list not on an integer.

Suggestion: If you just want to write a function that returns the value associated with awesome in the dictionary write

def awesome_count(dict):
    if 'awesome' in dict:
        return dict['awesome']
    return 0

Then call this function directly to your dictionaries.

if products['word_count'] is a list of dict , try this:

products = {}
products['word_count'] = [{'and': 5,'stink': 1, 'because': 2}, 
                          {'awesome': 3, 'bad': 2}, 
                          {'mac': 5, 'awesome': 1}]

products['awesome'] = [d.get('awesome',0) for d in products['word_count']]

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