Introduction to YAML slides

Hello, in the slides of the lesson in object there is a repetition for the “Blue Corvette” item.

If I understand the context of the slide, then you are looking at a list of dictionary. So the repeat of Blue Corvette is actually allowed; the record is repeated at different indexes of the list. The repetition shows you that you can do that in a list of dictionary.

Cool, thanks. I thought that duplicates were not admitted.

In a dictionary of dictionaries, keys will be unique. But in a list of dictionaries, there’s nothing to prevent duplicates.

This is not specific to YAML. In computer science, this is data structure theory. YAML (and JSON because JSON is YAML) implement two of these classic data structures

  • List (or array) - An unordered collection of values. Duplicates are allowed
  • Dictionary (or hash table) - An unordered collection of key-value pairs. Keys are unique, values don’t have to be.

A value can be a scalar type (number, string, boolean etc), or itself another list or dictionary.

In the car example, it is a list of dictionaries. The list value is a dictionary object describing each car. The list values do not have to be unique, so it is allowed to have the blue corvette in there twice.

How YAML handles duplicate keys in a dictionary depends on the parser. Some will raise an error. Others will silently only store the value of the last occurrence of a duplicate key and discard all instances previously seen. This is how Kuberenetes works

Consider

key1: foo
key2: bar
key1: baz

When you load that in and then read it back, you will get

key2: bar
key1: baz

because the second value for key overwrites the first value.