Skip to content
Advertisement

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement