Random String Key Generator with defaultdict

  • Share this:

Code introduction


The function takes two arguments, arg1 and arg2. It uses collections defaultdict to create a dictionary to store lists of randomly generated strings. The function defines an auxiliary function generate_random_string internally, which uses the random and string modules.


Technology Stack : collections, random, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zebra(arg1, arg2):
    from collections import defaultdict
    import random
    import string

    def generate_random_string(length):
        letters = string.ascii_lowercase
        return ''.join(random.choice(letters) for i in range(length))

    result = defaultdict(list)
    for _ in range(arg1):
        key = generate_random_string(arg2)
        result[key].append(_)

    return result