user3809888
user3809888

Reputation: 407

Creating a python dictionary of dictionaries with comma-separated pairs of values

I have a big text file where the data is of the following format:

1   80,982  163,8164    170,2620    145,648
2   42,1689 127,9365
3   57,1239 101,3381    43,7313 41,7212
4   162,3924

So each line starts with 1, 2, 3, etc and is followed by comma separated pairs of values, which are separated by blank spaces

I want to create a dictionary that looks like this:

{'1':{'80':982, '163':8164, '170':2620, '145':648}, '2':{'42':1689, '127':9365}, '3':{'57':1239, '101':3381, '43':7313, '41':7212}, '4':{'162':3924} } 

And so on. This is to use Dijkstra's algorithm as described here: http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/

Upvotes: 0

Views: 1126

Answers (1)

DSM
DSM

Reputation: 353059

Seems straightforward enough:

d = {}
with open("data.dat") as fp:
    for line in fp:
        parts = line.split()
        d[parts[0]] = dict(part.split(",") for part in parts[1:])

gives

>>> d
{'4': {'162': '3924'}, '1': {'170': '2620', '163': '8164', '80': '982', '145': '648'}, '3': {'43': '7313', '41': '7212', '57': '1239', '101': '3381'}, '2': {'42': '1689', '127': '9365'}}

(If you really want the innermost values to be integers, you could use

    subparts = [part.split(",") for part in parts[1:]]
    d[parts[0]] = {k: int(v) for k,v in subparts}

or something -- you could do this all in one line but there's no need.)

Upvotes: 1

Related Questions