【问题标题】:How can I merge values in one dictionary as an item to another dictionary created inside a "for" loop?如何将一个字典中的值作为项目合并到在“for”循环中创建的另一个字典?
【发布时间】:2021-08-19 15:31:38
【问题描述】:

我正在为列表、循环和字典而苦苦挣扎。

基本上,我有两个“级别”的字典。第一个以单词为关键字,以该单词在给定句子中出现的次数作为值。像这样:

wordcount={'sort': 3, 'count': 3, 'wrap': 3, 'coin': 11}

接下来,我有一个 for 循环,它遍历这些单词的列表,并为每个单词创建一个带有许多附加属性的字典,即根据 Google N-grams 的单词出现:

for word in wordlist:

      url =f"https://books.google.com/ngrams/json?content= 
      {word}&year_start=1965&year_end=1975&corpus=26&smoothing=3"
      sleep(1)
      resp = requests.get(url)

            if resp.ok:
                results = json.loads(resp.content)[0]
                results_clean = {key: val for key, val in results.items() if key == "ngram" or key =="timeseries"}
                timeseries = {key: results_clean[key] for key in results_clean.keys() & {'timeseries'}}
                timeseriesvalues= list(timeseries.values())
                timeseriesmean=np.mean(timeseriesvalues)
                ngramsonly = {key: results_clean[key] for key in results_clean.keys() & {'ngram'}}
                ngramsvalues = list(ngramsonly.values())
                results_nouns_final={"word": ngramsvalues, "occurrence_mean": timeseriesmean}

基本上,我想附加到 results_noun_final 之前那个单词的出现值。但是,当我尝试通过将 wordcount 中的单词值作为第三项添加到此字典中时(如下所示):

results_nouns_final={"word": ngramsvalues, "occurrence_mean": timeseriesmean, "count": wordcount.items()}

它正在附加 所有 个单词的计数,并给我如下内容:

{'word': ['sort'], 'occurrence_mean': 5.319996372468642e-05, 'count': dict_items([('sort', 3), ('count', 3), ('wrap', 3), ('coin', 11)}
{'word': ['count'], 'occurrence_mean': 4.5438979543294875e-05, 'count': dict_items([('sort', 3), ('count', 3), ('wrap', 3), ('coin', 11)}
...etc.

谁能告诉我哪里出错了?我想要的输出如下所示:

{'word': ['sort'], 'occurrence_mean': 5.319996372468642e-05, 'count': 3}
{'word': ['count'], 'occurrence_mean': 4.5438979543294875e-05, 'count': 3}

非常感谢任何可以提供帮助的人!

胡安

【问题讨论】:

  • “当我尝试通过将 wordcount 中的单词值作为第三项添加到此词典中来这样做时……它正在附加所有单词的计数”……嗯,是的,这就是 @ 987654328@ 表示。我不认为我理解这个问题。您有一个名为wordcount 的dict,并且您想查找与特定键对应的值,是吗?你肯定知道怎么做吗? (提示:results_clean[key] 是什么意思?)你肯定知道如何找出你要找的钥匙吗? (提示:可能与ngramsvalues有关?)

标签: python loops dictionary nlp n-gram


【解决方案1】:

当您使用wordcount.items() 时,您将获得所有 wordcount 字典中的项目。您只想访问word 的计数。 尝试将循环中的最后一行替换为:

results_nouns_final={"word": ngramsvalues, "occurrence_mean": timeseriesmean, "count": wordcount.get(word)}

wordcount.get(word) 为您提供字典中word 的计数。如果word 不在wordcount 中,则使用.get() 返回None。

如果您确定字典中存在每个单词,则可以使用wordcount[word]。

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 2016-10-05
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2021-05-15
    相关资源
    最近更新 更多