ORM
ORM

Reputation: 25

Create a dictionary out of a text file

For example, lets say we have a .txt file named letters which contains,

a
b
b
c
d
d
d
d

How would I go about creating a dictionary in which the keys are the individual letters found in the file and the values are the number of times each letter appears? For example, a would be a key and the corresponding value would be 1, while b is also a key and its value is 2.

We just started learning opening files and creating dictionaries so I would assume I would start with something like,

file = open('letters.txt', 'rt') 

I am not quite sure if the rt part is right, but then we would have to search 'file' so,

for letter in file:

But I'm not quite sure how to search for letters, make them keys, and then add the number of times the letter occurs to the value in a dictionary. Any advice?

Upvotes: 0

Views: 95

Answers (2)

KT.
KT.

Reputation: 11430

If it were a practical problem, you should probably have done something like:

from collections import Counter
counts = Counter([ln.strip() for ln in open('letters.txt')])

or even

counts = Counter(open('letters.txt').read())

(this will also count newline characters).

As you are apparently doing a learning exercise, you are probably looking for something like:

counts = dict()
for line in open('letters.txt'):
    letter = line[0]
    counts[letter] = counts.get(letter, 0) + 1

Upvotes: 1

AChampion
AChampion

Reputation: 30258

Python has a convenient extension to dict in the collections module called Counter that does exactly what you are looking for:

>>> from collections import Counter
>>> with open('letters.txt') as f:
...     c = Counter(map(str.strip, f))
>>> c
Counter({'a': 1, 'b': 2, 'c': 1, 'd': 4})

If you really want it as a dict:

>>> dict(c)
{'a': 1, 'b': 2, 'c': 1, 'd': 4}

Upvotes: 1

Related Questions