I understand this isn't strictly valid YAML, but I'm wondering how I could modify my pyyaml parser to group the values associated with duplicate keys into a list.
So, I have the following:
import yaml
from io import StringIO
data = """
NAME: Best Test
TEST: True
More: Yes
NO_LEADING_ZEROS: 0713
ENTITY:
Name: Great
Value: 10
ENTITY:
Name: Even better
Value: 11
"""
with StringIO(data) as f:
parsed = yaml.load(f.read(), Loader=yaml.BaseLoader)
print(parsed)
assert(isinstance(parsed.get("ENTITY"), list))
I get the following:
{'NAME': 'Best Test',
'TEST': 'True',
'ENTITY': {'Name': 'Even better', 'Value': '11'},
'More': 'Yes',
'NO_LEADING_ZEROS': '0713'}
Assuming I cannot change the "yaml" but only my parser, what would I change to get the following dictionary instead?
{'NAME': 'Best Test',
'TEST': 'True',
'ENTITY': [
{'Name': 'Great', 'Value': '10'}
{'Name': 'Even better', 'Value': '11'}],
'More': 'Yes',
'NO_LEADING_ZEROS': '0713'}
I've seen this answer which looks similar Getting duplicate keys in YAML using Python
But that solution did not work for my use case, in that it just made every field into a list, and returned this:
{'NAME': ['Best Test'],
'TEST': [True],
'ENTITY': [defaultdict(<class 'list'>,
{'Name': ['Great'], 'Value': [10]}),
defaultdict(<class 'list'>,
{'Name': ['Even better'], 'Value': [11]})],
'More': [True],
'NO_LEADING_ZEROS': [459]})