How to generate a random dictionary?

I need to create a dictionary with key and random values given a scope, i.e.

{key 1: value1, key 2: value2, key 3: value1, key 4: value 1, key 5: value 1}


{key 1: value2, key 2: value1, key 3: value1, key 4: value 1, key 5: value 1}


{key 1: value1, key 2: value1, key 3: value1, key 4: value 1, key 5: value 2}

...and so on

As you can see, the dictionary has the pattern below:

  • the key is generated from the input number of the function, if I input 5, I have 5 keys, if I input 3, I have 3 keys
  • the value has only 2 different values (value1 and value2), but value2 can only appear 1 time randomly in any key. The remaining values will be value1.


def function(n):
   from random import randrange
   mydict = {}
   for i in range(5):
         key = "key " + str(i)

   value = ['value1', 'value2']

Just default all the values to value1 first, and then randomly pick one key to change to value2:

def function(n):
   from random import randrange
   values = ['value1', 'value2']
   mydict = {"key " + str(i): values[0] for i in range(n)}
   mydict["key " + str(random.randrange(n))] = values[1]

   return mydict

Python, The choice function performs the task of random value selection and list method is The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2} The random pair is : ('is', 2) Please use, generate link and share the link here. Method #1 : Using random.choice () + list () + items () The combination of above methods can be used to perform this task. The choice function performs the task of random value selection and list method is used to convert the pairs accessed using items () into a list over which choice function can work. filter_none.

I think the fastest way would be to use the built-in dict.fromkeys() classmethod to create a dictionary full of value1 entries and then randomly change one of them.

import random

def function(n):
   mydict = dict.fromkeys(("key "+ str(i) for i in range(n)), 'value1')
   mydict["key "+ str(random.randrange(n))] = 'value2'  # Change one value.
   return mydict

print(function(3))  # -> {'key 0': 'value1', 'key 1': 'value1', 'key 2': 'value2'}
print(function(5))  # -> {'key 0': 'value2', 'key 1': 'value1', 'key 2': 'value1', 'key 3': 'value1', 'key 4': 'value1'}

Random-Word � PyPI, Advance Usage. To generate single random word we can use these optional parameters. hasDictionaryDef (string) - Only return words with dictionary definitions� Welcome to Random Word where you can find a random word of the day and much, much more. This website gives you the opportunity to learn new words every day to grow your vocabulary. If you're in a hurry, you can learn the first word that pops up as a word of the day, but you don't have to stop there.

You can simply try this:

>>> def func(n):
...   mydict = {}
...   for i in range(n):
...     mydict['key'+str(i)] = randrange(10)
...   return mydict
>>> print(func(5))
{'key0': 8, 'key1': 2, 'key2': 4, 'key3': 4, 'key4': 7}

How to get a random entry from a dictionary in Python, How to get a random entry from a dictionary in Python. Randomly choosing a key -value entry from a dictionary gives each entry equal selection probability. You can change how much random text Word generates by filling in what’s between the parentheses. To do that, you’ll use =Rand (x,y), where x is the number of paragraphs and y is the number of sentences in each paragraph. For example, if you want seven paragraphs that each contain four sentences, you’d use the following formula: =Rand (7,4)

similar to @Idlehands, but parametrized for n and actually returns the dict

def function(n):
    from random import randrange, randint
    mydict = {'key'+str(i):'value1' for i in range(n)}
    mydict['key'+str(randint(0,n-1))] = 'value2'
    return mydict


randomElement(), Call randomElement() to select a random element from an array or another collection randomElement(using:) , passing in the system's default random generator. If the dictionary doesn't contain the given key, accesses the provided default� There is a package random_word could implement this request very conveniently: $ pip install random-word from random_word import RandomWords r = RandomWords() # Return a single random word r.get_random_word() # Return list of Random words r.get_random_words() # Return Word of the day r.word_of_the_day()

Your question is not terribly clear to me, but I think this is what you are trying to do:

   from random import randrange
   mydict = {}
   value = ['value1', 'value2', 'v3', 'v4', 'v5']

   for i in range(5):
         key = "key " + str(i)
         mydict.update(key: value[i])

Your list either has to be 5 values long (or more) or your for loop has to iterate only twice.

Python random.sample() to choose multiple items from any sequence, Randomly select multiple items from a list, set, and dictionary. If you want to generate random samples without replacement out of a list or� Use randint () when you want to generate a random number from an inclusive range. Use randrange () when you want to generate a random number within a range by specifying step value. It produces a random number from an exclusive range. You should be aware of some value constraints of a randrange () function.

Generating Random Data in Python (Guide) – Real Python, You'll cover a handful of different options for generating random data in Python gold mine in a global Python dictionary that is not persistent between sessions. Finally, you can also generate a column of all confidentiality levels which is then mapped to the 200,000 claim_reasons column you just generated. To do so, you can use the previously defined claim_confidentiality_dict dictionary as a lookup reference to generate a confidentiality level at index i which is paired with the same index position of the claim_reasons list.

How to generate original creative ideas with random word stimulation, Not a dictionary on your computer – an actual old-fashioned “analog” book. You will also need a way to take notes – a pen and paper or computer� To generate list of random word we can use these optional parameters hasDictionaryDef (string) - Only return words with dictionary definitions (optional) includePartOfSpeech (string) - CSV part-of-speech values to include (optional) excludePartOfSpeech (string) - CSV part-of-speech values to exclude (optional)

This AI Generates Random Gibberish Words With 'Dictionary , The website even allows users to submit their own words where it can then generate dictionary definitions. The platform is powered by GPT-2, a� Try these simple steps to create random numbers: Create function: private int randomnumber(int min, int max) { Random rnum = new Random(); return rnum.Next(min, max); } Use the above function in a location where you want to use random numbers. Suppose you want to use it in a text box. textBox1.Text = randomnumber(0, 999).ToString();

  • Is there any constraint on the number of key-value pairs that will be present in the dict?
  • @Idlehands The OP hasn't mentioned the total number of key-value pairs to be generated.
  • @taurus05 The number of keys would be dynamic based on description, but the constraint is that there will always be two values, and only one of them will be value2. If the conditions are changed we can revisit this solution.
  • Thanks. I made some changes and now it works!! def function(n): from random import randrange import random mydict = {} mydict = {"key " + str(i): 'value1' for i in range(1,n+1)} mydict["key "+ str(random.randrange(1,n+1))] = 'value2' return mydict
  • You could also just use str(random.randrange(n)+1) as well :)
  • Is fromkeys more efficient than a dict comprehension? Genuinely curious.
  • @Idlehands: I haven't actually timed the two, but fromkeys() is written in C, so is likely faster. Using Python's built-ins whenever possible is often a good way to improve performance.
  • You piqued my interest, so I timed it. For a dict generation of 100 keys with n=1000000 trial, the performance between fromkeys (53.68s) and dict comp (54.38s) are relatively comparable. IIRC comprehensions uses C code too so it should be similar.
  • @Idlehands: I guess that doesn't surprise me too much in this particular case because it's still generating the keys iteratively using user-supplied (i.e. relatively-slow interpreted) Python code.