I have the following YAML file named input.yaml
:
cities:
1: [0,0]
2: [4,0]
3: [0,4]
4: [4,4]
5: [2,2]
6: [6,2]
highways:
- [1,2]
- [1,3]
- [1,5]
- [2,4]
- [3,4]
- [5,4]
start: 1
end: 4
I'm loading it using PyYAML and printing the result as follows:
import yaml
f = open("input.yaml", "r")
data = yaml.load(f)
f.close()
print(data)
The result is the following data structure:
{ 'cities': { 1: [0, 0]
, 2: [4, 0]
, 3: [0, 4]
, 4: [4, 4]
, 5: [2, 2]
, 6: [6, 2]
}
, 'highways': [ [1, 2]
, [1, 3]
, [1, 5]
, [2, 4]
, [3, 4]
, [5, 4]
]
, 'start': 1
, 'end': 4
}
As you can see, each city and highway is represented as a list. However, I want them to be represented as a tuple. Hence, I manually convert them into tuples using comprehensions:
import yaml
f = open("input.yaml", "r")
data = yaml.load(f)
f.close()
data["cities"] = {k: tuple(v) for k, v in data["cities"].items()}
data["highways"] = [tuple(v) for v in data["highways"]]
print(data)
However, this seems like a hack. Is there some way to instruct PyYAML to directly read them as tuples instead of lists?