【问题标题】:updating multiple lists from a single dictionary entry using a for loop使用 for 循环从单个字典条目更新多个列表
【发布时间】:2019-11-14 14:46:46
【问题描述】:

我有一个键列表(存储为字符串:str1、str2、str3...),我想从字典中获取。从技术上讲,我正在使用 jsonlines 流式传输 100,000 个字典(Twitter 推文)。

我需要将每个键的值存储在单独的值列表中(每个列表是一个键的名称),我已经创建为 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'

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

【问题讨论】:

  • 我怀疑您未在此处的代码中包含的 duplication_check 是字符串而不是列表。此外,从引发错误的行开始,查看该行及其上方的行。我也看不出你从哪里确定“迭代”的起点。
  • 抱歉,我只发布了一半的代码重复检查是一个列表,迭代只是当前处理的推文数量——我将它用作长时间运行的进度跟踪器
  • 供任何查看此内容的人将来参考 - 除了底部列出的错误之外,代码完全可以工作 - 这是我的查询

标签: python string list dictionary variables


【解决方案1】:

如果我不得不猜测,因为您发布的代码中似乎缺少一些东西

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

itemslistofkeys 中的一个字符串,你不能在这样的字符串上附加任何东西

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

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

【讨论】:

  • 可悲的是,这就是我的想法——我想我应该问的是“有没有办法将字符串转换为变量以允许这段代码工作”
  • @JamesHulse 使用项目作为键创建列表字典。使用新建议编辑答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 2021-02-09
  • 2020-08-29
  • 1970-01-01
  • 2023-01-25
  • 2018-02-16
  • 2016-07-29
相关资源
最近更新 更多