简体   繁体   中英

looping through a list of dictionaries to check if each dictionary contains a particular key

I am using python3, trying to loop through a list of dictionaries to check where each dictionary contains the key "retweeted_status." Currently, my code is:

for item in tweets_data:
if 'retweeted_status' in item:
    retweets2.append(item)
else: 
    pass

The type error I get is:

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-38-8c0e9225c623> in <module>() 1 for item in tweets_data: ----> 2 if 'retweeted_status' in item: 3 retweets2.append(item) 4 else: 5 pass TypeError: argument of type 'int' is not iterable .

tweets_data is a list containing tweets from a text file. To create this list, I opened and read the text file. For each line in the text file, I used json.loads(line) and saved the result from json.loads(line) to a variable. I then appended that saved result tweets_data .

I don't understand the error entirely. Does this mean that the item is not iterable?

The way I'm imagining this code to work is that it is iterating over my list of dictionaries (so, each item is a dictionary)...so why would the dictionary need to be iterable? Any explanation would be super helpful.


so, it turns out that for whatever reason my tweets_data was not completely a list of dictionaries and contained integers as people suggested below in the comments

Hard to say what's wrong with your code without seeing all the values of variables you have in it.

However, this is a shorter and more "pythonic" way of doing what your want.

new_list = [dict for dict in list_of_dicts if "retweeted_status" in dict]

here's your answer.. I've put a dummy list of dictionaries for testing, your data very likely is structured differently, but the procedure should not be too different

new_list = []
list_of_dict = [{'name':'dict 1'},{'retweeted_status':True},{'name':'dict 3'}]
for item in list_of_dict:
  if 'retweeted_status' in item:
    new_list.append(item)

print new_list

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