potentialwjy
potentialwjy

Reputation: 163

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}

or

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

or

{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:

Code:

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

   value = ['value1', 'value2']

Upvotes: 4

Views: 13336

Answers (11)

iGian
iGian

Reputation: 11203

Just for fun:

import random
n = 4
v1, v2 = 1, 2
res = dict(zip([ f"key{n}" for n in [x for x in range(1,n+1)] ], [ f"value{n}" for n in sorted([v1 for _ in range(n-1)] + [v2], key=lambda k: random.random()) ]))

Upvotes: 0

blhsing
blhsing

Reputation: 107134

You can pick a number first, and then use a dict comprehension to generate the desired dict with values based on whether the index is equal to the picked number or not:

def function(n):
    pick = randrange(n)
    return {'key %d' % i: ('value1', 'value2')[i == pick] for i in range(n)}

Upvotes: 0

martineau
martineau

Reputation: 123531

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'}

Upvotes: 2

r.ook
r.ook

Reputation: 13898

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

Upvotes: 6

gold_cy
gold_cy

Reputation: 14226

You could also increase another wrinkle of randomness as shown below:

from random import randint, sample

def pseudo_rand_dict(n):
    d = dict()
    r = randint(n, n ** n)
    for i in range(n):
        d[f'key_{i}'] = r
    to_change = sample(d.keys(), 1)[0]
    d[to_change] = randint(n, n * r)
    return d

d = pseudo_rand_dict(5)

print(d)

{'key_0': 2523, 'key_1': 2523, 'key_2': 2523, 'key_3': 9718, 'key_4': 2523}

Upvotes: 0

Ömer Metin
Ömer Metin

Reputation: 11

def randDict(n):
    from random import randint

    keys  = ["key"+str(i) for i in range(n)]
    values = ["value"+str(i) for i in range(n)]
    final_dict={}
    for key in keys:
        final_dict[key]=values.pop(randint(0,n))

    return final_dict

Upvotes: 0

Ilia Gilmijarow
Ilia Gilmijarow

Reputation: 1020

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

print(function(5))

Upvotes: 1

Reedinationer
Reedinationer

Reputation: 5774

There are already a few options, but this is what I came up with:

import random
def my_function(n):
    mydict = {}
    value2_index = random.randint(0, n-1)
    for i in range(n):
        key = "key " + str(i)
        if i == value2_index:
            value = ['value2']
        else:
            value = ['value1']
        mydict.update({key: value})
    return mydict
thing = my_function(5)
print(thing)

It's not the cleanest or most beautiful, but I think it makes sense and is easily readable!

Running it once gave me:

{'key 3': ['value1'], 'key 4': ['value1'], 'key 2': ['value1'], 'key 1': ['value2'], 'key 0': ['value1']}

Upvotes: 0

C.Nivs
C.Nivs

Reputation: 13136

You could do it with a dict comprehension and numpy.random:

def create_dict(size=5):
    values = ['value_1', 'value2']

    # choose our index randomly
    x = lambda x: np.random.randint(1, len(values)+1)

    # the 1 in x() is a dummy input var
    return {"key %d"%i: values[x(1)] for i in range(size)}

Upvotes: 0

user
user

Reputation: 21

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.

Upvotes: 0

itismoej
itismoej

Reputation: 1847

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}

Upvotes: 3

Related Questions