Reputation: 705
I have a problem similar to this, however I do not know what the term is
cat = 5
dog = 3
fish = 7
animals= [cat, dog, fish]
for animal in animals:
# by animal name, I mean the variable name that's being used
print(animal_name + str(animal))
It should print out
cat5
dog3
fish7
So I am wondering if there is an actual method or function I could use to retrieve the variable name being used as a string.
Upvotes: 8
Views: 76335
Reputation: 363596
You are basically asking "How can my code discover the name of an object?"
def animal_name(animal):
# here be dragons
return some_string
cat = 5
print(animal_name(cat)) # prints "cat"
A quote from Fredrik Lundh (on comp.lang.python) is particularly appropriate here.
The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care — so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)…
….and don’t be surprised if you’ll find that it’s known by many names, or no name at all!
Just for fun I tried to implement animal_name
using the sys
and gc
modules, and found that the neighbourhood was also calling the object you affectionately know as "cat", i.e. the literal integer 5, by several names:
>>> cat, dog, fish = 5, 3, 7
>>> animal_name(cat)
['n_sequence_fields', 'ST_GID', 'cat', 'SIGTRAP', 'n_fields', 'EIO']
>>> animal_name(dog)
['SIGQUIT', 'ST_NLINK', 'n_unnamed_fields', 'dog', '_abc_negative_cache_version', 'ESRCH']
>>> animal_name(fish)
['E2BIG', '__plen', 'fish', 'ST_ATIME', '__egginsert', '_abc_negative_cache_version', 'SIGBUS', 'S_IRWXO']
For unique enough objects, sometimes you can get a unique name:
>>> mantis_shrimp = 696969; animal_name(mantis_shrimp)
['mantis_shrimp']
So, in summary:
animal_name
is implemented in my example, look here.dict
, as others have mentioned. This is the best choice when you actually need to use the name <--> object association.Upvotes: 18
Reputation: 4425
It was too old question, but for verity we can use
[name for name, obj in globals().items() if eval(name) in animals]
['cat', 'dog', 'fish']
cat = 5
dog = 3
fish = 7
animals= [cat, dog, fish]
Upvotes: 0
Reputation: 895
A different form of fadop3's answer
cat = 5
cat = '%s' % cat
This turns the cat
variable into a string.
Upvotes: 0
Reputation: 29312
You're confusing the variable name with the string of the animal name:
In here:
cat = 7
cat is the variable, 7 its value
In:
cat = 'cat'
cat is still the variable and 'cat' is the string with the animal name. You can put whatever string you like inside cat even cat = 'dog'
.
Now back to your problem: you want to print out the name of an animal and a correposnding number.
To pair name and number the best choice is to use a dict
, a dictionary. the {
and }
are representing a dict (just to be complete also a set
in some cases):
d = {3: 'cat', 5: 'dog', 7: 'fish'}
d
is your variable. {3: 'cat', 5: 'dog', 7: 'fish'}
is your dictionary. 3, 5, 7
are the keys of such dictionary and 'cat', 'dog', 'fish'
are the corresponding values.
Now you nedd to iterate on this dictionary. That can be done calling d.items()
:
d = {3: 'cat', 5: 'dog', 7: 'fish'}
for key,value in d.items():
print(value, key)
I reversed the value, key order diring printing to print the name before the number.
Upvotes: 0
Reputation: 4522
Instead of putting the variables into a list, I would put them into a dictionary.
d={}
d['cat']=5
d['dog']=3
d['fish']=7
for item in d.keys():
print item+' '+d[item]
Upvotes: 1
Reputation: 184455
Use a dictionary rather than a bunch of variables.
animals = dict(cat=5, dog=3, fish=7)
for animal, count in animals.iteritems():
print animal, count
Note that they may not (probably won't) come out in the same order you put them in. You can address this using collections.ordereddict
or just by sorting the keys if you merely need them in a consistent order:
for animal in sorted(animals.keys()):
print animal, animals[animal]
Upvotes: 5
Reputation: 29932
myAnimals = {'cat':5,'dog':3,'fish':7}
animals = ['cat','dog','fish']
for animal in animals:
if myAnimals.has_key(animal): print animal+myAnimals(animal)
Upvotes: 1
Reputation: 11906
I would change to using a dictionary variable that would let you easily map string names to values.
animalDict['cat'] = 5
animalDict['dog'] = 3
Then you can interate through the keys and print out what you want.
Upvotes: 0