From: why t. l. s. <yam...@wh...> - 2002-09-07 20:34:36
|
Mike Orr (ir...@ms...) wrote: > In contrast, Python dictionaries do not preserve the order at all. If > you print a dictionary or do dic.keys(), they come out in a random > order. Sometimes this is frustrating because it means you have to keep > a separate list around to show which order you want the elements > processed in. Of course, there's no concept of sorting a dictionary > in Python. You'd have to get the keys as a list and sort that. Ruby is the same. There's a new !ruby/pairs type in the latest YAML.rb that solves this by leveraging the seq-map shortcut in YAML. Here's the example from the YAML Cookbook: test: The !ruby/pairs type brief: > The sequence-mapping shortcut in YAML allows you to place the first line of the mapping on the same line as the dash for the entry containing the mapping. The !ruby/pairs type takes advantage of this shortcut to create (instead of a sequence including maps) a single object of pairs which can be accessed like an ordered hash. Entries in which the last value in the pair is null can simply show the first value in the pair. yaml: | --- !ruby/pairs - Minh Thai: 22.95 - Guus Razous-Schultz: 24.32 - Zoltan Labas Hungary: 24.49 - Lars Petrus - Ken`ichi Ueno Japan ruby: | winners = YAML::Pairs.new winners[ 'Minh Thai' ] = 22.95 winners[ 'Guus Razous-Schultz' ] = 24.32 winners[ 'Zoltan Labas Hungary' ] = 24.49 winners[ 'Lars Petrus' ] = nil winners[ 'Ken`ichi Ueno Japan' ] = nil winners _why |