简体   繁体   中英

How to dynamically add 2 different lists to a dictionary in python

I have a dictionary with keys and empty values, and I also have a function that takes random items from a list. I would like for every dictionary key to have two lists as a value, and the lists should be filled with the results of the function that takes random items from the list. So what I have:

import random

dict = {
'User1': None,
'User2': None, 
'User3': None,
}

list = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']

def randomitems():
    return random.sample(list, 3)

And I would like the output to be:

    dict = {
'User1': [3 random items from list] [3 random items from list],
'User2': [3 random items from list] [3 random items from list], 
'User3': [3 random items from list] [3 random items from list],
}

Thank you

Is it something like this what you are looking for? You cant assign two arrays to a dict like you described, you would have to have the seperate arrays in another array, concat them or place them in a dict.

import random

dict = {
'User1': None,
'User2': None, 
'User3': None,
}

list = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']

def randomitems():
    return random.sample(list, 3)
for key in dict.keys(): # For every key in dictionary
    dict[key] = [randomitems(),randomitems()] #Set dict item(User(X)) to an array containing two arrays of 3 random items[3 random items from list]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM