简体   繁体   English

使用逗号分隔的值对创建字典的python字典

[英]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 因此,每一行均以1、2、3等开头,后跟逗号分隔的值对,并用空格隔开

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/ 这将使用此处描述的Dijkstra算法: http : //code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/

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.) 或类似的东西-您可以在一行中完成所有操作,但是没有必要。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM