1

I apologize in advance if my question is too standard. I tried my best to google the answer but could not find a satisfying one.

I have a distance matrix file in Jason with the following format

{"A": {"A":0, "B": 1, "C": 2}, "B":{"A": 1, "B": 0, "C": 1}, "C":{"A": 2, "B":1, "C":0}}

This tells the distance between any two pairs. For example, the distance from A to B is 1. How can I convert this one into a matrix form in Python?

Thank you!

tungprime
  • 51
  • 1
  • 5

1 Answers1

2

Before coding, we can overview your data and define your problem:

You have vertices:

vertices = ["A", "B", "C"]

So the expected matrix is a 3 x 3 2d-array (3 = number of your vertices)

It looks like:

matrix = [
[0, 1, 2],  // edges's values staring from vertex A (edges: AA, AB, AC)
[1, 0, 1], // edges's values starting from vertex B (BA, BB, BC)
[2, 1, 0], // edges's values starting from vertex C (CA, CB, CC)
]

Your mission is now to build the matrix above by code, not by eyes :D. So the solution is:

  • Define your vertices
  • Build (number_of_vertices x number_of_vertices) matrix
data = {'A': {'A': 0, 'B': 1, 'C': 2}, 'B': {'A': 1, 'B': 0, 'C': 1}, 'C': {'A': 2, 'B': 1, 'C': 0}} # Just a quick example, you can search how to read from file later

vertices = data.keys() # Your vertices is the dictionary's keys, use Python built-in method.
number_of_vertices = len(vertices)  # Count your vertices

matrix = []

for vertex1 in vertices:
  row = []  # Initialize a row represent values for edges starting from vertex1 to other vertices
  for vertex2 in vertices:
    row.append(data[vertex1][vertex2])  # Edge "vertex1" -> "vertex2"
  matrix.append(row)  # Add to our matrix

print(matrix)
# [[0, 1, 2], [1, 0, 1], [2, 1, 0]]

I used two for ... in loops for clearer demonstration. When you get used to, you can shorten by searching & using List Comprehension in Python.

nghiaht
  • 775
  • 4
  • 12