user3318660
user3318660

Reputation: 303

Convert string to int value python

I want to convert a string to a specific int value in Python i.e. "red" I want to be 1, "blue" to 2, etc. I am currently using if-else statements. I have a dataset of strings with common strings that I want to associate with a number. Please help.

def discretize_class(x):
    if x == 'first':
        return int(1)
    elif x == 'second':
        return int(2)
    elif x == 'third':
        return int(3)
    elif x == 'crew':
        return int(4)

Upvotes: 0

Views: 692

Answers (3)

Roundhouse
Roundhouse

Reputation: 98

Your question is a bit vague, but maybe this helps.

common_strings = ["red","blue","darkorange"]
c = {}
a = 0
for item in common_strings:
    a += 1        
    c[item] = a
# now you have a dict with a common string each with it's own number.

Upvotes: 0

Abhijit
Abhijit

Reputation: 63707

Assuming, by datasets, you either mean a

  • text file
  • database table
  • a list of strings

So first thing importantly, you need to know, how you can read the data. Example for

  • test file: You can simply read the file and iterate through the file object
  • database table: Based on what library you use, it would provide an API to read all the data into a list of string
  • list of strings: Well you already got it

Enumerate all the strings using the built-in enumerate

Swap the enumeration with the string

Either use dict-comprehension (if your python version supports), or convert the list of tuples to a dictionary via the built-in `dict

with open("dataset") as fin:
    mapping = {value: num for num, value in enumerate(fin)}

This will provide a dictionary, where each string, ex, red or blue is mapped to a unique number

Upvotes: 0

Ohumeronen
Ohumeronen

Reputation: 2086

You need to use a dictionary. That would be best I think:

dictionary = {'red': 1, 'blue': 2}
print dictionary['red']

Or with the new code you added just now:

def discretize_class(x):

    dictionary = {'first': 1, 'second': 2, 'third': 3, 'crew': 4}
    return dictionary[x]

print discretize_class('second')

Upvotes: 3

Related Questions