9 ms·
Here is a fun little thing I didn't realize before running into it: OrderedDict(a=1, b=2).keys() Is not guaranteed to return ['a', 'b']. Of course this m
by IgorPartola 10y ago
Here is a fun little thing I didn't realize before running into it:
OrderedDict(a=1, b=2).keys()
Is not guaranteed to return ['a', 'b'].
Of course this makes sense, but is annoying nonetheless.
- toyg 10y ago[for k in OrderedDict("a"=1, "b"=2)] should give you what you want, IIRC
- the_mitsuhiko 10y agoThat's not even valid Python.
- deleted 10y ago[deleted]
- coldtea 10y agoWell, [k for k in OrderedDict(a=1, b=2)] not that different in valid Python
- mark-r 10y agoBut as pointed out elsewhere, kwargs aren't guaranteed to be in order, so by the time the OrderedDict is built it's already wrong. It seems the change we're discussing was primarily motivated by a desire to fix that specific problem.
- ak217 10y agoThe point OP is making is that none of these statements will guarantee the order of insertion, since OrderedDict must take the variadic kwargs input as a dict, which is inherently unordered. You have to use a list of tuples.
- coldtea 10y agoYes, agree, just wanted to give the correct Python for the (still) ill attempt at traversing OrderedDict keys in order.
- deno 10y agoSyntaxError: keyword can't be an expression You want to pass a list of tuples: from collections import OrderedDict assert list(OrderedDict([('a', 1), ('b', 2)]).keys()) == ['a', 'b']
- philh 10y agoThe problem isn't that .keys() isn't returning them in order. The problem is that the kwargs (a=1, b=2) aren't passed to OrderedDict() in order, so the constructor has no way of knowing which one should be first.
- fovc 10y agoI think the standard answer is to use > OrderedDict([('a', 1), ('b', 2)]) I find myself doing that and similar things (objects with `key` and `value` attributes) to deal with JSON non-ordering a lot. I can definitely see value in preserving keyword argument order
- yes_or_gnome 10y agoIn 3.6, this will be ordered. Python creates a dict out of the keywords arguments, so before 3.6, this creates the old hash-ordered dict which is covered to an OrderedDict. But, as the other commenter mentioned, a list of 2-tuples is the safe bet.