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

Python datastructure for keys being mapped to auto-increment integer value

I want to store a list of strings into a dictonary data structure, where the key will be the string I provided, and the value will be an auto-increment count.

text = ['hello', 'world', 'again']
ai_ds = {} # define the data structure here, used dict just for reference
ai_ds.add(text[0]) # should return 0
ai_ds.add(text[1]) # should return 1

auto_increment_ds.get(text[0]) # should return 0

I could do this by keeping a manual counter and then using that when inserting values in a dictionary, but I wanted to know if there is any default data structure like this in python.

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 :

A dict with setdefault will work fine:

d = {}
d.setdefault("a", len(d))
d.setdefault("b", len(d))
d.setdefault("a", len(d))
print(d) # a=0, b=1
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