6

How can I create new variables with the names and values coming from a list?

This:

name = ['mike', 'john', 'steve']   
age = [20, 32, 19]  
index = 0

for e in name:
    name[index] = age[index]
    index = index+1

...of course does not work. What should I do?

I want to do this:

print mike
>>> 20

print steve
>>> 19
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1496868
  • 63
  • 1
  • 1
  • 3
  • 6
    [You should keep data out of your variable names.](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) Use a dictionary instead. – Sven Marnach Jul 03 '12 at 22:12
  • 1
    Strongly agree with Sven. Don't do this. If you think you have an exceptionally good reason then (a) you probably don't but (b) tell us what it is just in case. (It can be done, but I urge anyone reading this not to explain how unless the OP has given a good enough reason.) – Gareth McCaughan Jul 03 '12 at 22:14
  • Well, i have a lot of widgets in pygtk (from glade), named: entry_name, entry_secondname, entry_age etc. Normally i import it like this: `self.entry_name = self.wTree.get_widget("entry_name")` `self.entry_secondname = self.wTree.get_widget("entry_secondname")` But i wanted to automatized it in loop. Wrong way? – user1496868 Jul 03 '12 at 22:26
  • @user1496868: If it's `self`, then you can assign to `self.__dict__[somename]` instead. – Ry- Jul 03 '12 at 22:35
  • 2
    Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea Jul 02 '20 at 01:26

4 Answers4

13

I think dictionaries are more suitable for this purpose:

>>> name = ['mike', 'john', 'steve']   

>>> age = [20, 32, 19] 

>>> dic=dict(zip(name, age))

>>> dic['mike']
20
>>> dic['john']
32

But if you still want to create variables on the fly you can use globals()[]:

>>> for x,y in zip(name, age):
    globals()[x] = y


>>> mike
20
>>> steve
19
>>> john
32
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
5

You can use globals():

globals()[e] = age[index]

Generally, though, you don't want to do that; a dictionary is much more convenient.

people = {
    'mike': 20,
    'john': 32,
    'steve': 19
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • No, you can't use `vars()`. See the documentation. It returns `locals()`, and the return value of `locals()` must not be modified. (It will work by chance if `locals()` happens to coincide with `globals()`.) – Sven Marnach Jul 03 '12 at 22:16
  • 1
    @SvenMarnach: Oops, thanks. It is now "fixed". Not that I recommend it anyways. – Ry- Jul 03 '12 at 22:19
0

A dictionary is the way to go!

import pandas as pd
import datetime
import pandas_datareader as dr

# Get data for this year, so far
start = datetime.datetime(2019,1,1)
end = datetime.datetime(2019,6,1)

companies = ['AA', 'AAPL', 'BA', 'IBM']
df_dict = {}
for name in companies:
    df_dict[name] = pd.DataFrame()
    df_dict[name] = dr.data.get_data_yahoo(name, start, end)

print()
print(' Apple dataframe ')
print(df_dict['AAPL'].head())
cobrp
  • 11
  • 3
  • 1
    An explanation would be in order. E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/56513491/edit), not here in comments (*** *** *** *** *** ***[without](https://meta.stackexchange.com/a/131011)*** *** *** *** *** *** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Aug 21 '23 at 10:58
-1
name = ['mike', 'john', 'steve']   
age = [20, 32, 19] 
for i in range(len(name)):
    exec("%s = %d" %(name[i], age[i]))
print(mike)
print(john)
print(steve)
  • 2
    Please give some information about what your code does. – Bobface Jun 28 '18 at 21:15
  • Can you make this work for values that are strings - eg, suppose age was ['Twenty', 'Thirty two', 'Nineteen'] – Tapa Dipti Sitaula Jul 13 '18 at 11:36
  • This is a poor solution, playing into OP's [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). It's OK to add this purely for completeness, but one must state the caveat that 99.9% of the time, this is not desirable. Such a caveat is not present here. – ggorlen Aug 21 '23 at 15:48