1

I have list of tuples with 3 elements. I want to convert it into a dict with preserved order.

>>> a = [('one', '0', '1'), ('two', '0', '0'), ('three', '1', '1')]
>>> x = OrderedDict({sb[0]: sb[1:] for sb in a})
>>> x
OrderedDict([('three', ('1', '1')), ('two', ('0', '0')), ('one', ('0', '1'))])

I see order getting changed, not sure why. Can someone please help me fix this issue?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
npatel
  • 1,081
  • 2
  • 13
  • 21

1 Answers1

3
...{...}..

Oops.

OrderedDict(((sb[0], sb[1:]) for sb in a))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • You don't need one set of those parens; when the only argument to a function (or constructor in this case) is a genexpr, the call parens double as the genexpr parens, so this works fine: `OrderedDict((sb[0], sb[1:]) for sb in a)`. The important part is removing the `{}` (that make it a `dict` comprehension), because if you make a `dict` first, you've already lost the order, so `OrderedDict` can't recover it. – ShadowRanger Nov 08 '17 at 01:04