0

File:

 1 2,5 3,1
 2 4,10 1,5
 3 4,1 1,1
 4 2,10 3,1

I'd like to create dictionary as follows:

{1:[[2,5], [3,1]], 2:[[4,10], [1,5]], 
 3: [[4,1], [1,1]], 4: [[2,10], [3,1]]}

I managed to achieve this:

{1: [['2,5'], ['3,1']], 2: [['4,10'], ['1,5']], 
 3: [['4,1'], ['1,1']], 4: [['2,10'], ['3,1']]}

Using the following code:

f = open("file.txt")
D = {}

for line in f:
    line = line.strip().split(" ")   
    for i in line:
        D[int(line[0])] = [[x] for x in line[1:]]
print D
4
  • 4
    So instead of [x] you want something like map(int, x.split(','))? Commented Aug 13, 2015 at 15:31
  • I want dict to look like exactly as the first one containing only integers in lists, just look the example. Commented Aug 13, 2015 at 15:32
  • 1
    I did "just look the example". So, have you tried what I just suggested?! Commented Aug 13, 2015 at 15:33
  • Yes, I am doing it now. Commented Aug 13, 2015 at 15:35

1 Answer 1

2
f = open("file.txt")
D = {}

for line in f:
    line = line.strip().split(" ")   
    for i in line:
        D[int(line[0])] = [[int(y) for y in x.split(',')] for x in line[1:]]
print D

Edit: tested. Should work fine :)

Because your original code contains a list comprehension I'm going to assume you understand them. All I did was turn [x] into [int(y) for y in x.split(',')]. I.e., ['3,4'] ->[3,4].

Sign up to request clarification or add additional context in comments.

1 Comment

Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.