Advertisement
gruntfutuk

random text keys and class instances

Oct 20th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None | 0 0
  1. 'example code creates a dictionary of class instances with random text keys'
  2.  
  3. from random import choices, randint
  4. import string
  5.  
  6. class Example():
  7.     def __init__(self):
  8.         self.num = randint(1, 100)
  9.  
  10. def unique_key(size, instances):
  11.     while True:
  12.         key = ''.join(choices(string.ascii_lowercase +
  13.                              string.digits, k = size))
  14.         if key not in instances:
  15.             return key
  16.  
  17.  
  18. size = 10  # number of instances I require
  19.  
  20. instances = {}
  21. for _ in range(size):
  22.     instances[unique_key(size, instances)] = Example()
  23.  
  24. for name, instance in instances.items():
  25.     print(f'{name}: random number: {instance.num}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement