Question

How can I take data from a text file in the following format:

abc 5
defg 8
ghi 58
jklmn 450
opqrstuv 8456

And add it to a dictionary. For example: the first would be dictionary['abc']=5, the last one would be dictionary['opqrstuv']=8456 and so on. I need to add all the data (every linein the text file)

Was it helpful?

Solution

dictionary = {}
with open('path/to/file') as infile:
    for line in infile:
        key,value = line.split(" ")
        dictionary[key] = int(value)

In other words, read the file line by line, and set the dict such that each key is the area before the single space and each value is the area after that single space cast as an int.

If you'll always have LETTERS NUMBERS then you could do this with regex, but it seems unnecessarily difficult.

As always with dictionary mappings, try to think about what you're going to want as standard behavior if keys collide, e.g. if I read "abc 5" but already have "abc 10" earlier in the file, so dictionary["abc"] exists.

(If you like, here's the ugly-as-hell regex solution:

import re
from operator import itemgetter as iget
with open('path/to/file') as infile:
    data = infile.read() # UGH
re_data = re.findall(r"([^\d\s]+)|([\d]+)", data)
dictionary = dict(zip( map(iget(0),re_data[0::2]),map(int,map(iget(1),re_data[1::2])) ))
# DOUBLE UGH. As a rule of thumb, if you're using three map
# functions in one line, REFACTOR.

OTHER TIPS

dictionary={}
with open('file.txt','r') as f:
    for line in f.readlines():
        a,b = line.split()
        dictionary[a] = int(b)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top