Search code examples
pythondictionarydefaultdict

How to give unique integer id starting from 0 to random given number?


What I want to implement in Python:

# 1. define int_factory

# 2. get new id of value 123 --> give 0 to 123
a = int_factory[123]
print(a)  # = 0

# 3. get new id of value 12324 --> give 1 to 12324
a = int_factory[12324]
print(a)  # = 1

# 4. Hey, what's 123's id?
a = int_factory[123]
print(a)  # = 0

# 5. get new id of value 513 --> give next id, which is 2 to 513
a = int_factory[513]
print(a)  # = 2

I'd like to implement it using a dictionary data type, or defaultdict in Python.

What I tried:

In [2]: def func():
   ...:     for i in range(10**15):
   ...:         yield i
   ...:

In [3]: a = defaultdict(func)

In [4]: next(a[123])

But this doesn't work.

Is there a more elegant way to implement this in Python?


Solution

  • I would do it following way:

    import collections
    import itertools
    cnt = itertools.count()
    int_factory = collections.defaultdict(cnt.__next__)
    print(int_factory[123])
    print(int_factory[12324])
    print(int_factory[123])
    print(int_factory[513])
    

    Output:

    0
    1
    0
    2
    

    Explanation: You need to deliver callable when creating collections.default_dict, which will return desired value for missing key