Creation of Graph in Dictionary form returning integers

Asked

Viewed 257 times

3

I am implementing a Python code for Graph creation

with open (filename, "r") as f:
    d = {}
    for line in f:
        key, value = line.split()
        if key not in d:
            d[key] = [value]
        else:
            d[key].append(value)

However my algorithm is returning the string dictionary and not whole, look at my output:

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

how do I convert the whole key and value or get everything as an integer?

  • There is some error or just the output is not as expected?

  • only the output should generate a Graph with integers and not string.

  • Do you want both the key and the value as integers? Or just the values? (if you want the key too, use int also in key, just be careful to do that before you test your presence on dict, not after)

1 answer

3

You are reading a file. Natural that they are strings.

To type to integer, modify your code to the following:

with open (filename, "r") as f:
    d = {}
    for line in f:
        key, value = line.split()
        if key not in d:
            d[key] = [int(value)]
        else:
            d[key].append(int(value))

Browser other questions tagged

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