Can I assume an order in a series of structured keys of a python dict?

49 views Asked by At

I have a python dictionary d whose keys are formatted date strings like 20101231 etc. Now, when I run for key in d.keys(): ..., can I always assume earlier dates will appear earlier in the loop?

Comparing dates in string format is automatically consistent with string comparison, which means if date A is earlier than date B, then A's string representation is smaller than B's. Now since dictionary keys are stored according to their hash value order, do smaller strings always have smaller hash values than bigger strings?


EDIT: Short answer, no, don't assume this. Code:

import pandas as pd
ts = pd.date_range(start='20100101', periods=1000)
ts_str = [t.strftime("%Y%m%d") for t in ts]
ts_dict = {date: 0 for date in ts_str}
key_list = [key for key in ts_dict.keys()]

Now print key_list to see how erratic it is...

0

There are 0 answers