如何将一个字典中的值作为一个项目合并到另一个在 "for" 循环中创建的字典中?

How can I merge values in one dictionary as an item to another dictionary created inside a "for" loop?

我正在努力处理列表、循环和字典。

基本上,我有两本'levels'字典。第一个以一个词作为键,以该词在给定句子中出现的次数作为值。所以像这样:

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.items() 时,您将获得 所有 wordcount 词典中的项目。您只想访问 word 的计数。 尝试将循环中的最后一行替换为:

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

wordcount.get(word) 为您提供字典中 word 的计数。如果 word 不在 wordcount.

中,则使用 .get() returns None

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