Posts

Showing posts with the label Collections

Changing Order Of Ordered Dictionary In Python

Answer : OrderedDicts are ordered by insertion order. So you would have to construct a new OrderedDict by looping over the key:value pairs in the original object. There is no OrderedDict method that will help you. So you could create a tuple to represent the idea order of the keys , and then iterate over that to create a new OrderedDict . key_order = ('animal', 'people', 'food', 'drink') new_queue = OrderedDict() for k in key_order: new_queue[k] = queue[k] Or more eloquently OrderedDict((k, queue[k]) for k in key_order) Edit: You can write a custom function (warning, this works but is very quick and dirty): EDIT: Fixed bug that occurs when you try to move forward import collections def move_element(odict, thekey, newpos): odict[thekey] = odict.pop(thekey) i = 0 for key, value in odict.items(): if key != thekey and i >= newpos: odict[key] = odict.pop(key) i += 1 return odict queue = ...

Arrays.asList() Vs Collections.singletonList()

Answer : Collections.singletonList(something) is immutable whereas Arrays.asList(something) is a fixed size List representation of an Array where the List and Array gets joined in the heap. Arrays.asList(something) allows non-structural changes made to it, which gets reflected to both the List and the conjoined array. It throws UnsupportedOperationException for adding, removing elements although you can set an element for a particular index. Any changes made to the List returned by Collections.singletonList(something) will result in UnsupportedOperationException . Also, the capacity of the List returned by Collections.singletonList(something) will always be 1 unlike Arrays.asList(something) whose capacity will be the size of the backed array. I would just add that the singletonlist is not backed by an array and just has a reference to that one item. Presumably, it would take less memory and can be significant depending on the number of lists you want to create. Th...