0

I need to make if statements dependent on the key position inside the dictionary.

Ideally I'd have something like this:

for key in dict:

    #setup things based on key value

    if key==first key in dict:
      #do smth order dependent

    elif key==last key in dict:
      #do smth order dependent

    else:
      #do smth order dependent

But as dictionaries in Python 2.x aren't ordered, I can't retrieve elements directly by index position.

So if the for loop iterates through the dict in the order of key creation (was filled based on 'keylist'), I could do something like this:

for key in dict: 

    #setup things based on key value

    if key==keylist[0]: #the list/tuple the dict keys were created from gets referenced here
      #do smth order dependent

    elif key==keylist[-1]:
      #do smth order dependent

    else:
      #do smth order dependent 

If the order wasn't the same as of the keylist, I'd need to split the for loop into two, so the first one can fill a new list in the order the loop iterated through the dict(as kind of a counter), so the second one can do stuff based on this real order.

for key in dict:

    #setup things based on key value

    new_keylist.append(key) 

for key in new_keylist:
    if key==new_keylist[0]:
      #do smth order dependent

    elif key==new_keylist[-1]:
      #do smth order dependent

    else:
      #do smth order dependent 

Do I need to go this extra mile? Thanks for clarification in advance.

hghtch
  • 3
  • 1
  • "But as dictionaries in Python 2.x aren't ordered, I can't retrieve elements directly by index position" you can't do that in Python 3 either – juanpa.arrivillaga Jul 12 '20 at 04:43

1 Answers1

0

Dictionaries were unordered in Python 2.x; you should use a separate ordered dictionary implementation if you need predictable behavior.

Perhaps see also Do dicts preserve iteration order if they are not modified?

Even in 3.6+ this is implementation-lependent; use OrderedDict if you want to rely on this behavior. See https://gandenberger.org/2018/03/10/ordered-dicts-vs-ordereddict/

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks for the reply. Unfortunately, as I'm using the Python shipped with Houdini, I am bound to the version and libraries that ship with it (not sure how I'd use pip on it), so I guess I'll have to do the workaround I envisioned. – hghtch Jun 06 '20 at 21:28