Issue
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.
Solution
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/
Answered By - tripleee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.