Lucky's Creations
Lucky's Creations

Reputation: 13

Splitting an array of words into characters using a dictionary

So far, I have read a file (which is a poem)and split that poem so that each element of an array is each word of the poem(ex: ['Hey', 'diddle','diddle'...etc.]

Now I need to run through that array and input, for example, words[0] into a dictionary to create wordDict = {H:1,E:1,Y:1}. Each word is going to be evaluated to have the number of each letter as the key value depending on how many times it appears in the word (ex: apple = wordDict = {a:1,p:2,l:1,e:1}).

wordDict = {};
for word in words:
    for letter in word:
        wordDict[letter] = 0 ; 
return wordDict;

Above is what I have so far but all this does is print every letter of the poem as the key and the key value = 0 (just to test). I also need for wordDict to be redefined everytime a new word is evaluated.

I tried to explain this as best as I could, but if you need clarification please comment to let me know.

Upvotes: 1

Views: 1091

Answers (4)

Aaditya Ura
Aaditya Ura

Reputation: 12669

You can try this without importing any module :

file1=['Hey', 'diddle','diddle']

track=0
for words in file1:
    result = {}

    for chara in words:
        if chara not in result:
            result[chara]=track
        else:
            result[chara]+=track

    print(result)

output:

{'H': 0, 'y': 0, 'e': 0}
{'d': 0, 'i': 0, 'l': 0, 'e': 0}
{'d': 0, 'i': 0, 'l': 0, 'e': 0}

Upvotes: 1

RoadRunner
RoadRunner

Reputation: 26315

You can try using map() and collections.Counter():

import collections

words = ['Hey', 'diddle', 'diddle']

print(list(map(dict, map(collections.Counter, words))))

Which outputs:

[{'y': 1, 'e': 1, 'H': 1}, {'i': 1, 'l': 1, 'e': 1, 'd': 3}, {'i': 1, 'l': 1, 'e': 1, 'd': 3}]

Upvotes: 1

Alam
Alam

Reputation: 403

words = ['apple', 'banana']
allwordsList=[]
for word in words:
    wordDict = {};
    for letter in word:
        wordDict[letter] = 1 if letter not in wordDict else wordDict[letter] + 1; 
    allwordsList.append(wordDict)
print(allwordsList)

This would give you

[{'a': 1, 'p': 2, 'l': 1, 'e': 1}, 
 {'b': 1, 'a': 3, 'n': 2}
]

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249153

import collections
words = ['Hey', 'diddle', 'diddle']
[collections.Counter(word) for word in words]
# or list(map(collections.Counter, words))

Gives you:

[Counter({'H': 1, 'e': 1, 'y': 1}),
 Counter({'d': 3, 'e': 1, 'i': 1, 'l': 1}),
 Counter({'d': 3, 'e': 1, 'i': 1, 'l': 1})]

Upvotes: 1

Related Questions