Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading