-1

The Dictionary parm should contain all the keys ['f', 'r', 'b', 'l', 't','u'] and only then the below should happen. The below mentioned iteration prints in an unexpected order, please correct what's wrong.

parm = {'r':'r', 'l':'l', 't':'t', 'u':'u', 'f':'f', 'b':'b'}
if all(key in parm for key in ['f', 'r', 'b', 'l', 't','u']):
  parm = [_ for _ in parm.values() for i in range(0,9)]
  print (parm)

Returns:

['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 't', 't', 't', 't', 't', 't', 't', 't', 't']

Expected:

['f',  'f',  'f',  'f',  'f',  'f',  'f',  'f',  'f',  'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 't', 't', 't', 't', 't', 't', 't', 't', 't', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u',]
martineau
  • 119,623
  • 25
  • 170
  • 301
Prabhanjan
  • 155
  • 2
  • 10
  • 1
    Dupe of https://stackoverflow.com/questions/15479928/why-is-the-order-in-dictionaries-and-sets-arbitrary. And your code is still invalid. – DYZ Sep 27 '18 at 01:24
  • Update the code, it is valid now – Prabhanjan Sep 27 '18 at 01:29
  • The order of items in a dictionary was undefined in versions of Python before 3.6. To preserve order in earlier versions use [`collections.OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict) instead of a regular `dict`. – martineau Sep 27 '18 at 01:31
  • 1
    You appear to be depending on fetching dictionary values in a certain order. Dictionaries don't work that way in all but the most recent versions of Python (which 2.x certainly isn't). – John Gordon Sep 27 '18 at 01:32
  • Also, why did you expect the values to be returned in that order? That's how they're ordered in the list, but so what? That has no connection. – John Gordon Sep 27 '18 at 01:44

1 Answers1

1

Your list comprehension produces items according to the order of the values of the parm dict (which is pretty arbitrary prior to Python 3.6), so naturally it won't follow the order of the keys you use in the condition for the if statement. If you want the keys to be reordered in the same way as the keys used in the condition you should make it a separate list and use it for both the condition and the list comprehension:

parm = {'r':'r', 'l':'l', 't':'t', 'u':'u', 'f':'f', 'b':'b'}
keys = ['f', 'r', 'b', 'l', 't','u']
if all(key in parm for key in keys):
  parm = [parm[key] for key in keys for i in range(0,9)]
  print (parm)
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Good alternative to using `collections.OrderedDict` (which might not be possible in all circumstances). – martineau Sep 27 '18 at 01:40