How do I make 2 lists correspond to each other?

Viewed 645

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.

7 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

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

You can also use index(). Dictionary version, however, is better and cleaner for the typical key-value situation.

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

idx = list1.index

if list2[idx('happy')] < list2[idx('sad')]:
    print('sad')
else:
    print('happy')

You can use a dictionary in python. A simple way to represent a key-value pair. Ex: did = {'jack': 4098, 'sape': 4139} click on it for better understandinghow to use dictionary

You can just use simple dict for data mapping

emotions = {'happy': 2, 'sad': 5,  'grumpy': 6, 'mad': 9}


if emotions['happy'] > emotions['sad']:
    print("you are happy")
else:
    print("you are sad")

You may use the standard enum module to accomplish it:

from enum import IntEnum

class Mood(IntEnum):
    happy = 2
    sad = 5
    grumpy = 6
    mad = 9

if Mood.happy > Mood.sad:         # Nonsense; do you mean "if yourmood < Mood.sad:"?
    print ("you are happy")

If you don't want to use a dictionary, you can use exec function.

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

for L,i in zip(list1,list2):
  exec('{}={}'.format(L,i))

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

Notice here that you must use strings to name the variables (you can't have a list of unassigned variables).

Related