0

I have a dictionary with empty values. I would like the values of the dictionary to be lists with 2 random items from another list of attributes but if the first random attribute is either attribute1 or attribute2 then the second random attribute can't be attribute1 or attribute2 again. Also in general it the 2 attributes in the list can't be the same. This is what I have right now:

import random

elem_list = ['Elem1', 'Elem2', 'Elem3']
dict_1 = dict.fromkeys(elem_list)
attributes = ['attribute1', 'attribute2', 'attribute3', 'attribute4']
attributes2= ['attribute3', 'attribute4']

#First elem in value list for dictionary is random
for elem in dict_1:
    dict_1[elem] = [random.choice(attributes)]
#2nd is dependent
for elem in dict_1:
    if dict_1[elem] == 'attribute1' or 'attribute2':
        for elem in dict_1[elem]:
            elem.append(random.choice(attributes2))

print(dict_1)

So in the end dict_1 should look something like this:

dict_1 = {
    'Elem1': ['attribute1', 'attribute3'],
    'Elem2': ['attribute2', 'attribute4'],
    'Elem3': ['attribute3', 'attribute4'
}

1 Answer 1

1

there are various problems with your script such as:

instead of

if dict_1[elem] == 'attribute1' or 'attribute2':

you probably mean this:

if dict_1[elem][0] == 'attribute1' or dict_1[elem][0] == 'attribute2':

Please try to isolate the problems you have and describe them in more detail instead of posting your whole script.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.