3 ms·
> I hate that many other languages, including C#, Ruby and Python, force me to choose between either an unordered map or a list of (key, value) tuples Another
by halflings 12y ago
> I hate that many other languages, including C#, Ruby and Python, force me to choose between either an unordered map or a list of (key, value) tuples
Another commenter mentioned Python's OrderedDict, and Ruby's hashtables are ordered (from 1.9+):
https://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/ https://www.igvita.com/2009/02/04/ruby-19-internals-ordered-...
It looks like C# also has an OrderedDictionary class:
http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx http://msdn.microsoft.com/en-us/library/system.collections.s...
I never had to use any of these classes even if I do use hashmaps all the time, so IMHO the Python way is best (default to a 'normal' unordered hashmap, offer an ordered alternative)
- mduerksen 12y agoThanks for the pointers! I find myself needing this surprisingly often: An array of elements in a certain order which I also want to lookup by Id. Sometimes the order is defined by configuration, sometimes by some other criteria that is not accessible for this particular component, so I can't resort to a SortedHashMap. Still, I need a 1) fast and 2) convenient way of lookup by some key. Convenience is often more important to me than performance in those cases, since the data size is not huge, but I hate it when I have to write array.find(e => e.Key == myKey) instead of orderedLookup[myKey].
- breuleux 12y agoI think there is one reason to default to something ordered, which is that iterating through unordered hashmaps can be non-deterministic from one run to the other. For instance, if you hash by id, the same objects may be assigned different ids from a run to the next, meaning that the map will be iterated in a different order. If there is a bug that's sensitive to iteration order, it will not be reproducible and that can be very annoying to debug.
- aidos 12y agoIf you've got bugs due to iteration order you have a whole other issue. If you know that iteration order is important, it should be explicit in the way you prepare/store/handle the data. If your code only works when you iterate in a specific order and you didn't deliberately define that order, it's only really working by accident. Don't get me wrong, it's actually a bug I've run into in the past, and you're right, the non-deterministic issue makes it harder to debug. But when I discovered it I blamed myself for not being explicit with my constraints.
- deleted 12y ago[deleted]