vendredi 24 avril 2020

Creating a random value in the dictionary while looping over a list and appending

I need to create a dictionary structure in the below format.

list_1 = [1,2,3,4,5]

list_2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

list_3 = random.sample(list_2 , random.randint(0,len(list_2))

Loop as the len(list_1) and need to loop using list_2 and then using the random sample created using list_3, assigning each value of the list_3 as a value in the inner dictionary below, while iterating.

*Needed dictionary format:

my_dict = { 1: { 1: a, 
                 2:b, 
                 3,c},
             2: { 1: 'd',
                  2: 'g'},
             3: {1, 'e',
                 2, 'f',
                 3, 'g'}
                .....
               }*

My code:

list_1 = [1,2,3,4,5]

list_2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

list_4= []

j= 1

while i <= len(list_1):

    list_3 = random.sample(list_2 , random.randint(0,len(list_2))

    for k in list_3:

        my_dict= { i: { j: k, 
                      }
                 }

        j+=1

    i+=1

    list_3 = random.sample(list_2 , random.randint(0,len(list_2))
    list_4.append(my_dict)

The jth value should increment after every iterating of list_3 and keep adding a new jth key + value (k) After the loop ends of list_3, another sample list (list_3) should be created and the above same repeats in the new ith key and gets added to the dictionary.

I am not getting the required result and need help if anyone can fix the code.

Thank you!




Aucun commentaire:

Enregistrer un commentaire