Based on the description above, I would skip the step of creating the dictionary. If you start from non-empty dictionary, then run the code above. Once it is set up, use bisect
and insert
as below.
new_item = randrange(10)
new_key = 'key' + str(new_item)
# find the index where to insert
idx = bisect.bisect(sort_mydic, (new_key, -1)) # the second argument should be smaller than any value
# check if the key is already used or not
if idx == len(sort_mydic) or sort_mydic[idx][0] != new_key:
sort_mydic.insert(idx, (new_key, new_item))
else:
# update the value -- as in dictionary
sort_mydic[idx] = (new_key, new_item)
In case you need to retrieve an item.
def get_item(key):
idx = bisect.bisect(sort_mydic, (key, -1))
if idx == len(sort_mydic) or sort_mydic[idx][0] != key:
return None # there is no such item
else:
return sort_mydic[idx][1]