1

I have the following variables:

  • A list called word_frequencies that has the same dictionary with all values 0, at each position of the list.
  • A list called all_preprocessed_articles that has a vector that contains all the words from a particular article, at each position of the list. (Thus, len(word_frequencies) = len(all_preprocessed_articles))

The dictionary is a set of all the words in all the articles.

I have Initialised the list item, with all the dictionary items as follows:

word_frequencies = []

for word in vocab:
    temp_frequency_dict.update({word:0})

for i in range(0, num_articles): 
    word_frequencies.append(temp_frequency_dict)

With the following code, I am aiming to iterate through each vector i in all_preprocessed_articles and changing the dictionary i in the word_frequencies list for that word, by adding 1 to the value of that particular word (key).

for i in range(0, num_articles):
    current_article = all_preprocessed_articles[i]
    for word in current_article:
        word_frequencies[i][word] += 1

What I expect as output is that each dictionary in word_frequencies shows the frequencies for each word in that specific article. However, what it outputs is the same dictionary at each position in word_frequencies.

What can I do to so that the output is a list with i dictionaries in which each dictionary shows the occurrences per word in the corresponding article?

Emil
  • 1,531
  • 3
  • 22
  • 47
  • 1
    "'word_frequencies' that has the same dictionary with all values 0"- i think this is your mistake, initiate these as *different* dictionaries, likely you have many references to the *same* dictionary instead; please update to a clear minimal reproducible example too – Chris_Rands Apr 26 '18 at 13:19
  • I have initiated it as: for i in range(0, num_articles): word_frequencies.append(temp_frequency_dict) Where 'temp_frequency_dict' is a single dictionary. Is that the mistake, you mean? – Emil Apr 26 '18 at 13:22
  • Try `for i in range(0, num_articles): word_frequencies.append(dict(temp_frequency_dict))` – Chris_Rands Apr 26 '18 at 13:25
  • This is my first question on Stackoverflow. What do you mean by a 'minimal reproducible example'? – Emil Apr 26 '18 at 13:26
  • https://stackoverflow.com/help/mcve – Chris_Rands Apr 26 '18 at 13:26
  • Thanks a lot, now it works! – Emil Apr 26 '18 at 13:29
  • you're welcome , read this https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy and consider marking your question as a duplicate – Chris_Rands Apr 26 '18 at 13:37
  • 2
    Possible duplicate of [How to copy a dictionary and only edit the copy](https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy) – Emil Apr 26 '18 at 13:46

0 Answers0