1

I'm relatively new to coding in python so go easy on me.

I want to create integer variables with the names of these variables based off elements of a string array and set them all to zero to start with (in order to save me manually coding 20 variables out). The string array is shown below.

filterKeywords = ['IBM', 'Microsoft', 'Facebook', 'Yahoo', 'Apple',
  'Google', 'Amazon', 'EBay', 'Diageo',
  'General Motors', 'General Electric', 'Telefonica', 'Rolls Royce',  
  'Walmart', 'HSBC', 'BP',
  'Investec', 'WWE', 'Time Warner', 'Santander Group']

I don't want the variable names to be exactly the name of the element in the array, however, I want the variable names to contain the elements from the array, for example: for the string element 'apple' I want my variable name to be 'applePositive'. I have tried to implement this and here it is below (I'm not sure if it is the correct format or not).

for word in filterKeywords:
    [word + "Positive"] = 0

I'm getting a "cannot assign to operator" error with this and I've tried also to cast it to an int but it doesn't work either.

Any help would be much appreciated!

Chris
  • 1,206
  • 2
  • 15
  • 35
philmckendry
  • 555
  • 6
  • 21

2 Answers2

4

You're looking for a dict.

vars = {}
for word in filterKeywords:
    vars[word + "Positive"] = 0

Then use it however you want, for example, say, print vars["applePositive"].

You can access all your "names" with vars.keys()

You can do further computations on all the items too

for word, value in vars.iteritems():
    # do something
    print word, value

or

for i in vars:
    print i, vars[i]

And if at some point, you get suspicious if "applePositive" is in your dict and has a value, you can do 'applePositive' in vars, which will return either True or False.

And then if you decide to add 1 to the values of only Facebook and Apple, you can do that too

for i in ['applePositive', 'facebookPositive']:
    if i in vars:
        vars[i] += 1  
ComputerFellow
  • 11,710
  • 12
  • 50
  • 61
1

You can use a dic comprehension to put each value to a dictionary

filterKeywords = ['IBM', 'Microsoft', 'Facebook', 'Yahoo', 'Apple']
d = {k + "positive":0 for k in filterKeywords}

Which outputs:

{'IBMpositive': 0, 'Yahoopositive': 0, 'Microsoftpositive': 0, 'Facebookpositive': 0, 'Applepositive': 0}
Daniel
  • 5,095
  • 5
  • 35
  • 48