How to assign words to values in a list?

Viewed 354

I have a list with 4 different numbers, 10 numbers in total. To each of those numbers, I want to assign a color/word. The question is thus, how do I go from a list of numbers to a list of colors where every same number is represented by the same color/word?

Initial list:

my_list = [72, 50, 3, 50, 16, 72, 3, 72, 3, 50]

Expected output:

print(my_list) -> ['red', 'blue', 'green', 'blue', 'black', 'red', 'green', 'red', 'green', 'blue']

What did I try?

I extracted unique numbers from my_list:

my_list = [72,50,3,50,72,3,72,3,50]

UniqueList = list(set(my_list))
print(UniqueList)

Now I need to assign a color from a list of colors ['red', 'blue', 'green', 'black', 'yellow', 'purple'] to each of those 4 unique numbers and then generate my_list again with colors. Unfortunately I have no clue how to go forward. Any ideas?

2 Answers

You could create a lookup dictionary:

my_list = [72, 50, 3, 50, 16, 72, 3, 72, 3, 50]
colors = ['red', 'blue', 'green', 'black', 'yellow', 'purple']

lookup = dict(zip(set(my_list), colors))
output = [lookup[number] for number in my_list]
print(output)

Output

['red', 'green', 'black', 'green', 'blue', 'red', 'black', 'red', 'black', 'green']

You can consider the lookup dictionary as a function that assigns a color to one of the number. In the example above lookup has the following value:

{72: 'red', 16: 'blue', 50: 'green', 3: 'black'}

This means that it will assign 'red' each time 72 appears. You can customize lookup like this:

lookup = {72 : 'green', 50 : 'black', 3 : 'yellow', 16: 'purple'}

This time each time 72 appears green will be assigned. See more on how to create dictionaries in here.

Update

If you want to preserve the order of appearance in the list you could to the following:

seen = set()
result = []
for e in my_list:
    if e not in seen:
        result.append(e)
        seen.add(e)

print(result)

Output

[72, 50, 3, 16]

Notice that the list result is in order of appearance.

You can also provide a dict of {int: color} key value pairs and then do the following:

my_list = [72, 50, 3, 50, 16, 72, 3, 72, 3, 50]
mymap = {72: 'red', 50:'blue', 3:'green', 16:'black'}

print([mymap[k]for k in my_list])

## output
['red', 'blue', 'green', 'blue', 'black', 'red', 'green', 'red', 'green', 'blue']
Related