Assigning integers to strings

10,033

Use a dictionary.

d = {1: 'red', 2: 'orange', 3: 'yellow'}

Then you can do this to change the list:

lst = [d[k] for k in lst]

The dictionary basically 'maps' objects (in this case integers) to other objects, which is just what you want.

Share:
10,033
hayleyelisa
Author by

hayleyelisa

Updated on June 24, 2022

Comments

  • hayleyelisa
    hayleyelisa almost 2 years

    I'm working in Python and I have a list of integers: [1, 2, 1, 3, 2, 2, 1, 3].

    I want to assign each integer a string as if it were a variable: ['red', 'orange', 'red', 'yellow', 'orange', 'orange', 'red', 'yellow'].

    How would I go about doing this?

    In that example, 1 corresponds to 'red', 2 corresponds to 'orange', and 3 corresponds to 'yellow'.

    Thanks!