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:
JavaScript
x
13
13
1
import numpy as np
2
import random
3
import pandas as pd
4
5
customer = [1, 2, 3]
6
for k in customer:
7
priority = list(range(1,5)) # list of integers from 1 to 4
8
random.shuffle(priority)
9
print(priority) # <- List of unique random numbers
10
[4, 1, 3, 2]
11
[3, 1, 2, 4]
12
[4, 3, 1, 2]
13
but I want to have a dictionary like:
JavaScript
1
2
1
priority = {1:[4, 1, 3, 2], 2:[3, 1, 2, 4], 3:[4, 3, 1, 2]}
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:
JavaScript
1
19
19
1
import numpy as np
2
import random
3
import pandas as pd
4
5
customer = [1, 2, 3]
6
priority_dict = {}
7
for k in customer:
8
priority = list(range(1,5)) # list of integers from 1 to 4
9
random.shuffle(priority)
10
print(priority) # <- List of unique random numbers
11
priority_dict[k] = priority
12
#[4, 1, 3, 2]
13
#[3, 1, 2, 4]
14
#[4, 3, 1, 2]
15
16
print(priority_dict)
17
18
#{1: [3, 1, 4, 2], 2: [2, 1, 4, 3], 3: [1, 3, 2, 4]}
19