Title: Reading multiple lines in a file, and separating their values at the same time, to store it in dictionary
Tags: python;file;python-2.7;dictionary
Question: Hello I am beginner in python.
I have following file as "test.txt"
as so on .....
I want to read the values and store it to a dictionary
I have come up with following code but its not working
as [x.split(' ') for x in edges.readline().rstrip().split(' ')]can access only one line of the file.
Also this returns list on which int() typecasting can't be applied.
It can access multiple line in a loop but I would like to know pythonic way to do this.
connection = {(int(source),int(dest)):int(weight) for source,dest,weight in [x.split(' ') for x in edges.readline().rstrip().split(' ')]}
Can you please suggest the correct method to read this kind of file and then store it in a dictionary.
Thanks.

Here is the accepted answer: Here's a dict comprehension that's pretty clean, if a bit long:
with open("test.txt") as f:
connection = {(a, b) : c for a,b,c in (map(int, line.split()) for line in f)}
Note the use of a generator expression to iterate over the lines in the file instead of a list compherension - (map(int, line.split()) for line in f) vs [map(int, line.split()) for line in f]. This allows us to avoid having to store all of the files content in memory, which can be important if the file is large.
map is used to convert all the strings returned by line.split() to integers. I think using map here is nicer than the equivalent list comprehension: [int(x) for x in line.split()].
Here's the same logic broken up into its individual parts:
connection = {}
with open("test.txt") as f:
for line in f:
a,b,c = map(int, line.split())
connection[(a,b)] = c
To be truly equivalent with the dict comprehension, we'd need to create a generator function for iterating over the file:
def f_it(f):
for line in f:
yield map(int, line.split())
connection = {}
with open("test.txt") as f:
for a,b,c in f_it(f):
connection[(a,b)] = c


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:09/16/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><file><python-2.7><dictionary>', 'Title': 'Reading multiple lines in a file, and separating their values at the same time, to store it in dictionary', 'ViewCount': 343, 'id': 25879588, 'user_AboutMe': '<p>Trying to learn!</p>\n', 'user_AccountId': 3062879.0, 'user_DisplayName': 'mribot', 'user_Reputation': 499.0, 'user_Views': 79.0, 'user_id': 2595210.0}}