Home > Net >  create distance_matrix using python dictionaries
create distance_matrix using python dictionaries

Time:09-25

I'm working on a facility location problem model and i would like to create a dictionary containing this distance matrix,

distance_matrix

I want the keys to correspond to the combination between first element of each row and the header like this (kind of) "Spa" "SP_Andrimont" : 12275, "Spa" "SP_Pepinster" : 10626,81,...

So I was wondering, is it possible ? If yes, how would you go about it ? If not, what are the alternatives? New to python and programming here, so any help would be greatly appreciated.

thank you guyss

CodePudding user response:

It's not super clean but I wanted to provide an option that doesn't use external libraries. Here are the contents of test_csv:

city;SP_A;SP_B
A;5;2
B;6;3
C;2;7
D;7;3

And here is the code:

import csv

# Open csv file and add rows to list
with open('test_csv.csv', newline='') as file:
    rows = [row for row in csv.reader(file, delimiter=';')]

# Extract headers and indices (locations)
locations_a = [row[0] for row in rows[1:]]
locations_b = [header for header in rows[0][1:]]

# Create dict distance matrix
dist_matrix = {}
for i, loc_a in enumerate(locations_a):
    dist_matrix[loc_a] = {}
    for j, loc_b in enumerate(locations_b):
        dist_matrix[loc_a][loc_b] = rows[i 1][j 1]

# Print matrix
print(dist_matrix)
            
# Test location pair
print(dist_matrix['A']['SP_B'])

Output:

{'A': {'SP_A': '5', 'SP_B': '2'}, 'B': {'SP_A': '6', 'SP_B': '3'}, 'C': {'SP_A': '2', 'SP_B': '7'}, 'D': {'SP_A': '7', 'SP_B': '3'}}

and

2

If you want, you can do this a lot shorter with the pandas libary and its DataFrame.to_dict() method.

  • Related