使用for循环从单个字典条目更新多个列表

2024-04-16 12:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个键列表(存储为字符串:str1、str2、str3…),我想从字典中获取。从技术上讲,我使用jsonlines浏览了100000本字典(推特推特)

我需要将每个键的值存储在单独的值列表中(每个列表都是键的名称),我已经将其创建为empy列表(即list4str1、list4str2、list4str3…)

file = jsonlines.open(filename)
listofkeys = ['filter_level','created_at','favourite_count','retweet_count',(etc),]

tweet_texts = []
filter_level = []
created_at = [] 
favourite_count = [] 
retweet_count = []

for tweet in file 
    if tweet["text"] not in duplication_check:
        #What happens when a unique tweet is found 
        itteration += 1
        string = ("Tweet: " + str(itteration) + " :" + tweet["text"])
        duplication_check.append(tweet["text"])
        tweet_texts.append(string)
        uniquecount += 1

#_______THIS IS THE BIT I NEED HELP WITH______
        for items in listofkeys
            items.append(tweet[items])
#_______THIS IS THE BIT I NEED HELP WITH______


        if itteration%10000 == True & itteration != 1:
            print(itteration, " Items")
    else:
        #What happens when a copy is found
        copycount += 1
        itteration += 1 
        if itteration%10000 == True:
            print(itteration-1, " Items")

我得到以下错误:

AttributeError: 'str' object has no attribute 'append'

我不知道如何使用我有限的编码知识,因此需要帮助(也许有一个库或小生境功能?)


Tags: textin列表if字典countitemsfilter
1条回答
网友
1楼 · 发布于 2024-04-16 12:04:57

如果非要我猜的话,因为你发布的代码似乎少了一些东西

 for items in listofkeys
            items.append(tweet[items])

itemslistofkeys中的一个字符串。您不能向这样的字符串追加任何内容

一个好的解决方案是使用items字符串作为键创建列表字典

final_results = {}
for items in listofkeys
    if items not in final_results: 
        final_results[items] = [tweet[items]]
    else:
        final_results[items].append(tweet[items])

相关问题 更多 >