user1496868
user1496868

Reputation: 63

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

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

Upvotes: 6

Views: 33826

Answers (4)

cobrp
cobrp

Reputation: 9

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())

Upvotes: -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)

Upvotes: -2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251196

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

Upvotes: 13

Ry-
Ry-

Reputation: 225291

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
}

Upvotes: 5

Related Questions