shijuza
shijuza

Reputation: 301

Is it possible to use a tuple as a dictionary key in Python YAML?

dictionary = {('x1','y1'): [1,2], ('x2','y2'): [4,5], ('x3','y3'): [6,7]}

How do I configure this kind of dictionary in Python YAML?

Upvotes: 6

Views: 4824

Answers (1)

Kobi K
Kobi K

Reputation: 7931

One option is to create the your YAML file like:

!!python/tuple ['x1','y1']: [1,2]
!!python/tuple ['x2','y2']: [4,5]
!!python/tuple ['x3','y3']: [6,7]

And to load it:

import yaml

print yaml.load(stream=open("your_file_path", 'r'))

Output:

{('x1', 'y1'): [1, 2], ('x3', 'y3'): [6, 7], ('x2', 'y2'): [4, 5]}

To get some value you can use:

yaml_load[('x1', 'y1')]

And if you want to test it's a tuple just use:

type(yaml_load.keys()[0])

Upvotes: 3

Related Questions