Random Dictionary Generator from Lists

  • Share this:

Code introduction


This function accepts two arguments and generates a random dictionary by randomly selecting elements from two predefined lists as key-value pairs, and then returns the dictionary.


Technology Stack : pytest, random, collections.defaultdict

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import pytest
from collections import defaultdict

def test_random_dict(arg1, arg2):
    # This function takes two arguments and generates a random dictionary
    # from the two provided lists of keys and values, then returns the dictionary.
    keys = ['a', 'b', 'c', 'd']
    values = [1, 2, 3, 4]
    random_keys = random.sample(keys, min(len(keys), arg1))
    random_values = random.sample(values, min(len(values), arg2))
    random_dict = dict(zip(random_keys, random_values))
    return random_dict