I use ordered_set = dict() to create ordered set. The values are not important. Test is whether the key was already added only. Ordered set is a set of unique values where the order of adding is maintained.
if node not in ordered_set:
ordered_set[node] = None # ordered_set[node] = False or ordered_set[node] = '' or ordered_set[node] = 0
What is the most efficient way to add keys with empty values to dictionary? Maybe there is a better way to implement ordered set?
>Solution :
This is an approach. In later versions of Python (3.6+, I think), the order with which keys are added to a dictionary is maintained (the order of the keys in the dictionary could not be assured in earlier versions of Python).
The method .setdefault() is built into Python dictionaries and is designed for the use case you are faced with: check to see if a key exists and if not, create the key and set a default value.
mydict = {1: True, 2:True, 5: True}
for key in [1, 2, 3, 4, 5]:
mydict.setdefault(key, None)
yields
{1: True, 2: True, 5: True, 3: None, 4: None}
In the above, notice that the order of the keys is maintained … the first three keys already existed and other keys (3 and 4) are added in a specific order and the order is maintained.