Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make 2 lists correspond to each other? [duplicate]

I have 2 lists here:

list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

if happy > sad:
    print ("you are happy")

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

like image 638
conyieie Avatar asked Dec 04 '22 17:12

conyieie


2 Answers

You can zip the lists together and create a dict from them:

list1 = ["happy", "sad", "grumpy", "mad"]
list2 = [2, 5, 6, 9]

moods = dict(zip(list1, list2))
# This will create a dictionary like this
# {'happy': 2, 'sad': 5, 'grumpy': 6, 'mad': 9}


if moods["happy"] > moods["sad"]:
    print("You are happy")
else:
    print("You are sad")

The output is:

You are sad

Edit:

Another option would be directly choosing a mood if you don't care what the other values are (inspired by Laurent B. 's answer):

list1 = ["happy", "sad", "grumpy", "mad"]
list2 = [2, 5, 6, 9]

mood = list1[list2.index(max(list2))]
print("You are", mood)

Output:

You are mad
like image 94
Asocia Avatar answered Jan 15 '23 15:01

Asocia


An interesting way is to create a dict like this :

dico = {'happy':2, 'sad':5, 'grumpy':6, 'mad':9}
inv_dico = {v:k for k,v in dico.items()}

mood = inv_dico[max(dico['happy'], dico['sad'])]

print("you are : ", mood)
# you are : sad

note : you could use min instead of max to have the inverse effect

like image 42
Laurent B. Avatar answered Jan 15 '23 14:01

Laurent B.