Read txt with numbers and create a Python dictionary

Asked

Viewed 1,156 times

1

Good afternoon I’m trying to create a Graph from a Txt file but in the generated dictionary the numbers are coming out as if they were strings someone can help me , follows the code : txt file

`
0   1
1   2
1   4
1   5
2   3
2   6
3   2
3   7
4   5
4   0
5   6
6   5
6   7`

with open("/Users/jonnathanvinicius/Desktop/Trabalho PAA/cormen.txt","r") as f:    
G={}

    for line in f:
        u, v = line.split()
        if u not in G:
            G[u] = [v]
        else:
            G[u].append(v)
print "O Grafo Web-NotreDame foi Criado"

output from print {'1': ['2', '4', '5'], '0': ['1'], '3': ['2', '7'], '2': ['3', '6'], '5': ['6'], '4': ['5', '0'], '6': ['5', '7']}

1 answer

1

Just convert the characters to whole numbers.

u, v = map(int, line.split())

Changing this line results in

{0: [1], 1: [2, 4, 5], 2: [3, 6], 3: [2, 7], 4: [5, 0], 5: [6], 6: [5, 7]}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.