Modify

Ticket #79 (closed defect: wontfix)

Opened 6 years ago

Last modified 6 years ago

Multiple scalar values used as key creates Python hash error

Reported by: clay@… Owned by: xi
Priority: normal Component: pyyaml
Severity: normal Keywords: load list tuple hash
Cc:

Description

The YAML specification suggests that a mapping can have a key made of more than one item, as in

? - Detroit Tigers
  - Chicago cubs
:
  - 2001-07-23

However, when that data is imported via yaml.load(), PyYAML exits with a yaml.constructor.ConstructorError?, saying "found unacceptable key (list objects are unhashable)"

Is there a way to force multi-value keys to be processed as tuples instead of lists?

Attachments

Change History

comment:1 Changed 6 years ago by xi

  • Status changed from new to closed
  • Resolution set to wontfix

Yes, it's possible, using a custom constructor for yaml mappings.

For example, the following script

import yaml

data = """
? - Detroit Tigers
  - Chicago cubs
:
  - 2001-07-23
"""

def construct_yaml_map(loader, node):
    pairs = [(tuple(key) if isinstance(key, list) else key, value)
             for (key, value) in loader.construct_pairs(node, deep=True)]
    return dict(pairs)

yaml.add_constructor(u'tag:yaml.org,2002:map',
                     construct_yaml_map)

print yaml.load(data)

produces

{('Detroit Tigers', 'Chicago cubs'): [datetime.date(2001, 7, 23)]}
View

Add a comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
The resolution will be deleted. Next status will be 'reopened'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.