Home > Blockchain >  Counting the frequency of words in a list with a list of dictionaries
Counting the frequency of words in a list with a list of dictionaries

Time:12-07

I want to count the frequency of each unique string in a list and then append the results to a list of dictionaries, saving the string as the key and the value as the frequency of the string.

An example would be: input:

word_list=["I","am","bob","I","am","hungry"]

output:

dict_list=[{"I":2},{"am":2},{"bob":1},{"hungry":1}]

word_list=["I","am","bob","I","am","hungry"]
dict_list=[{"placeholder":0}]

for word in word_list:
    for i in range(len(dict_list)):
        if word not in dict_list[i].keys():
            dict_list.append({word:1})
            break
        elif word in dict_list[i].keys():
            dict_list[i][word] =1
            break

dict_list.pop(0)
print(dict_list)

#outputs is [{'I': 1}, {'am': 1}, {'bob': 1}, {'I': 1}, {'am': 1}, {'hungry': 1}]
#instead of [{"I":2},{"am":2},{"bob":1},{"hungry":1}]

CodePudding user response:

Code:-

word_list=["I","am","bob","I","am","hungry"]
hashmap={}
for word in word_list:
    hashmap[word]=hashmap.get(word,0) 1    
print(hashmap)

Output:-

{'I': 2, 'am': 2, 'bob': 1, 'hungry': 1}

CodePudding user response:

You can use:

from collections import Counter

out = [{k:v} for k,v in Counter(word_list).items()]
# or
# out = [dict([x]) for x in Counter(word_list).items()]

Output: [{'I': 2}, {'am': 2}, {'bob': 1}, {'hungry': 1}]

But honestly, what is the point of breaking a dictionary into a list a single item dictionaries?

The output of Counter(word_list) is far more useful:

Counter({'I': 2, 'am': 2, 'bob': 1, 'hungry': 1})

CodePudding user response:

You can use collections.Counter and a list comprehension to generate the result in one line like so:

from collections import Counter

word_list=["I","am","bob","I","am","hungry"]

dict_list = [{key: value} for key, value in Counter(word_list).items()]

print(dict_list)

Output:

[{'I': 2}, {'am': 2}, {'bob': 1}, {'hungry': 1}]

CodePudding user response:

You can import Counter from collections and set up a Couter for your word_list then convert it into a dict:

from collections import Counter

dict_list=Counter(word_list)

dict_list=dict(dict_list)

print(dict_list)

Output

>>> {'I': 2, 'am': 2, 'bob': 1, 'hungry': 1}
  • Related