Skip to content
Advertisement

Make dictionary from multiple list

I have a list of customers, and I want to generate a list of random numbers between 1 to 4 for each customer. I used the code below:

import numpy as np
import random
import pandas as pd

customer = [1, 2, 3]
for k in customer:
    priority = list(range(1,5))   # list of integers from 1 to 4
    random.shuffle(priority)
    print(priority)   # <- List of unique random numbers
[4, 1, 3, 2]
[3, 1, 2, 4]
[4, 3, 1, 2]

but I want to have a dictionary like:

priority = {1:[4, 1, 3, 2], 2:[3, 1, 2, 4], 3:[4, 3, 1, 2]}

How would I go about doing this in python?

Advertisement

Answer

Slight modifications to your existing loop is all you need. You can use your existing k to assign a new dictionary key & value:

import numpy as np
import random
import pandas as pd

customer = [1, 2, 3]
priority_dict = {}
for k in customer:
    priority = list(range(1,5))   # list of integers from 1 to 4
    random.shuffle(priority)
    print(priority)   # <- List of unique random numbers
    priority_dict[k] = priority
#[4, 1, 3, 2]
#[3, 1, 2, 4]
#[4, 3, 1, 2]

print(priority_dict)

#{1: [3, 1, 4, 2], 2: [2, 1, 4, 3], 3: [1, 3, 2, 4]}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement