user3059460
user3059460

Reputation: 23

Changing variable names on the go, in Python

I need help with a small part in my code, I'm a bit rusty.

It's hard to explain here but basically I need to switch between the variables, depending on their race etc., as I read through each of the records

Basically I want to rename variables as I go as there are a lot of variables for different categories, age, occupation, country, race etc..

So something like:

#(NewRecord[3] will have details of race)
if NewRecord[3] = "black"
var1 += blackcounter
else if NewRecord[3] = "white"
var1 += whitecounter`

could be:

for NewRecord[3] = "%s"
var1 += "%s"counter

??? How do I do this?

Aditional info...:

The programme I'm trying to make is an income predictor for people over and under 50k a year.

whiteCountUnder50
asianCountUnder50
indianCountUnder50
otherCountUnder50
blackCountUnder50

whiteCountOver50
asianCountOver50
indianCountOver50
otherCountOver50
blackCountOver50

#if white
overchance += (whiteCountOver50 / TotalPeopleOver)
underchance += (whiteCountUnder50 / TotalPeopleUnder)
print ("overchance: ", overchance)
print ("underchance: ", underchance)

#if black
overchance += (blackCountOver50 / TotalPeopleOver)
overchance += (blackCountUnder50 / TotalPeopleUnder)
print ("overchance: ", overchance)
print ("underchance: ", underchance)

#if asian
....

#if indian
....

etc...

Upvotes: 0

Views: 100

Answers (2)

Jules Gagnon-Marchand
Jules Gagnon-Marchand

Reputation: 3781

you can use dictionaries for this.

container = {}
#inserting arbitrary amount of black people
container["black"] = 254
#inserting arbitrary amount of white people
container["white"] = getWhitePeople()
print(str(container["white"]))
#prints whatever getwhitePeople() returned
container.update(getPairNewCategory())
#getPairNewCategory() returns {nameOfTheCategoryStringOrHash:initialValueInt}
print(str(container[nameOfTheCategoryStringOrHash]))
#prints whatever was in initialValueInt

what you are trying to do is basically this

counter = {}
for entry in NewRecord:
    if entry in counter:
        counter[entry] += 1
    else :
        counter[entry] = 1

However, the most pythonic way to do this is :

 from collections import Counter
 c = Counter(NewRecord)
 c["BlackOver50"] = 123123 #whatever the number of BlackOver50 entries in NewRecord

Upvotes: 2

Troy Rockwood
Troy Rockwood

Reputation: 6147

It's not completely clear what you want to do here but I think what you want is a dictionary. Here is a link to describe them: http://docs.python.org/2/tutorial/datastructures.html

You would do something like the following:

var1 += counter[NewRecord[3]]

Hope that helps.

Upvotes: 0

Related Questions