How to create new variables with names from list? This:
name = [\'mike\', \'john\', \'steve\']
age = [20, 32, 19]
index = 0
for e in name:
name[ind
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())
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
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)
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
}