cool77
cool77

Reputation: 1136

Adding to dictionary in a loop while reading file

I am wondering if there is a simple way to add dictionaries in a for loop while reading a file. I have a file.txt which i want to read it line by line and then add them into a dictionary. I tried the below but not able to actually add all the lines as key:value in the same dictionary.

content of file.txt
name1:value1
name2:value2
name3:value3


 with open("file.txt", 'r') as fd:
        for line in fd.readlines():
            d=dict([line.rstrip().split(":")])
            d.update(d)

Ultimately, i want my dictionary to have something like this: d = {'Name1': 'Value1', 'Name2': 'Value2', 'Name3': 'Value3'}

Any help is appreciated.

Upvotes: 0

Views: 2299

Answers (6)

helloV
helloV

Reputation: 52393

Fancy one liner assuming the file always exists and readable.

>>> dict(line.rstrip().split(':') for line in open('file.txt'))

{'name2': 'value2', 'name3': 'value3', 'name1': 'value1'}

Upvotes: 1

willnx
willnx

Reputation: 1283

No need to call 'readlines', file objects support the iter protocol. Calling 'readlines' will pull the whole file into memory

>>> d = {}
>>> with open('var.txt') as myfile:
...     for line in myfile:
...         name, val = line.split(':')
...         d[name] = val
... 
>>> d
{'name2': 'value2\n', 'name1': 'value1\n'}

You can drop the line returns on the dictionary values by doing:

d[name] = val.strip()

Upvotes: 3

khajvah
khajvah

Reputation: 5090

Here is another solution (it looks clearer to me):

>>> with open("sample", 'r') as fd:
...  for line in fd.readlines():
...   row = line.rstrip().split(":")
...   d[row[0]] = row[1]
... 
>>> d
{'name3': 'value3', 'me1': 'value1', 'name2': 'value2'}

Upvotes: 1

tdelaney
tdelaney

Reputation: 77347

On each iteration of the loop, you create a dict called d, try to update it with itself and then discard it. Since dict takes a sequence at initialization time, you can create it in one step

with open("file.txt", 'r') as fd:
    d = dict(line.rstrip().split(":") for line in fd)

Upvotes: 2

TheLazyScripter
TheLazyScripter

Reputation: 2665

Probably not the most efficient but it works! Good luck!!!

def createDict(fileName):
    '''
        Returns a dict of fileName
        '''
    data = {} #init dict
    file = open(fileName, 'rb').readlines() #open File and create list of each line
    for i in file: #loop through each file
        i = i.replace('\r', '').replace('\n', '').split(':') #replace all instances of \n and \r and split at :
        data[i[0]] = i[1] #add values to dict
    return data #return dict

Upvotes: 1

yurlungurrr
yurlungurrr

Reputation: 99

you need to declare the dict outside of the loop and update it inside. this is a scope issue.

 d={}
 with open("file.txt", 'r') as fd:
    for line in fd.readlines():
        d_tmp=dict([line.rstrip().split(":")])
        d.update(d_tmp)

Upvotes: 3

Related Questions