Make Dictionary From List
So I created a list like this: list = [line.strip() for line in open('file.txt','r')] This is a snippet of my list. [ '1 2', '2 3', '2 3', '4 3 1', '3 4', '5 4 2 1', '4 4',
Solution 1:
This should do the trick:
In [3]: arrs = [map(int, line.strip().split()) for line in open('file.txt')]
In [4]: first2rest = dict( (arr[0], arr[1:]) for arr in arrs)
In [5]: first2rest
Out[5]: {1: [2], 2: [3], 3: [4], 4: [4], 5: [7], 8: [3, 5, 2], 15: [11, 8, 9, 6, 3, 4]}
Let's take it apart. This part splits up each line in your file on spaces and converts them to ints:
map(int, line.strip().split())
Then this part creates the dictionary of the first item in the row to the rest:
first2rest = dict( (arr[0], arr[1:]) for arr in arrs)
However, as @SethMMorton pointed out, you will lose data as the file you listed includes the same key multiple times.
Post a Comment for "Make Dictionary From List"