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

Question:

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.

Asked By: adib.mosharrof

||

Answers:

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
Answered By: AKX

In case you string values are unique entries:

text = ['hello', 'world', 'again']
d = {}    
d[text[0]] = len(d)    
d[text[1]] = len(d)    
d[text[2]] = len(d)
print(d)

{'hello': 0, 'world': 1, 'again': 2}
Answered By: SOUBHIK RAKSHIT