Swift – Stored values order is completely changed in Dictionary

This is because of the definition of Dictionaries: Dictionary A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering. There is no order, they might come out differently than they were put in. This is comparable to NSSet. Edit: NSDictionary Dictionaries Collect … Read more

No generic implementation of OrderedDictionary?

Implementing a generic OrderedDictionary isn’t terribly difficult, but it’s unnecessarily time consuming and frankly this class is a huge oversight on Microsoft’s part. There are multiple ways of implementing this, but I chose to use a KeyedCollection for my internal storage. I also chose to implement various methods for sorting the way that List<T> does … Read more

Converting dict to OrderedDict

You are creating a dictionary first, then passing that dictionary to an OrderedDict. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dict is inherently not ordered. Pass in a sequence of tuples instead: ship = [(“NAME”, “Albatross”), (“HP”, 50), (“BLASTERS”, 13), (“THRUSTERS”, … Read more

Rename a dictionary key

For a regular dict, you can use: mydict[k_new] = mydict.pop(k_old) This will move the item to the end of the dict, unless k_new was already existing in which case it will overwrite the value in-place. For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely … Read more

Can I get JSON to load into an OrderedDict?

Yes, you can. By specifying the object_pairs_hook argument to JSONDecoder. In fact, this is the exact example given in the documentation. >>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(‘{“foo”:1, “bar”: 2}’) OrderedDict([(‘foo’, 1), (‘bar’, 2)]) >>> You can pass this parameter to json.loads (if you don’t need a Decoder instance for other purposes) like so: >>> import json >>> from collections … Read more