Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the most efficient way to add keys with empty values to dictionary?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading