dictionary - Python: Trying to create n dictionaries with randomly selected values from a range -
so i've tried:
import random r t = {'va1':r.randint(0,50),'va2':r.randint(0,15),'va3':r.randint(0,10)} n=15 _ in range(n): new_dict = {k:t k in range(n)} print(new_dict)
that gave me dictionary of random dictionaries t, weren't unique, dictionary full of 1 version of t.
what i'm looking dictionary keys 1,2,3...n , values dictionary t. need t different each iteration of loop.
thanks reading
python doesn't re-run dictionary literal because reference it. t
nothing more single dictionary created @ start.
the solution create new dictionary scratch in dictionary comprehension (both key , value expressions executed anew each iteration):
n=15 new_dict = {k: {'va1':r.randint(0,50),'va2':r.randint(0,15),'va3':r.randint(0,10)} k in range(n)} print(new_dict)
you may want put creating nested dictionary function:
def random_values_dict(): return {'va1':r.randint(0,50),'va2':r.randint(0,15),'va3':r.randint(0,10)} new_dict = {k: random_values_dict() k in range(n)}
note there little point in creating dictionary keys consecutive numbers starting @ 0. list more space efficient , have same performance characteristics mapping such numbers values:
new_list = [random_values_dict() k in range(n)]
new_list[0]
, new_dict[0]
both map generated dictionary in case.
Comments
Post a Comment