A1122
A1122

Reputation: 1354

Use strings in a list as variable names in Python

I have a list of string elements like user_contract = ['ZNZ6','TNZ6','ZBZ6']

I have a data set which has nested list structure like data = [[1,2,3],[4,5,6],[7,8,9]]

I want to assign each of the user_contract strings as variable names for each of the data nested list, in the respective order.

I know I can do this manually by typing ZNZ6, TNZ6, ZBZ6 = data. I don't think this is flexible enough, and I would have to manually change this line every time I change the names in user_contract.

Is there a way where I can make use of the user_contract variable to assign data to each of its elements?

Upvotes: 4

Views: 22126

Answers (3)

twinlakes
twinlakes

Reputation: 10258

You can use a dictionary comprehension to assign the values:

myvars = {user_contract[i]: data[i] for i in range(len(user_contract))}

Then you can access the values like so

myvars['TNZ6']
> [1, 2, 3]

Upvotes: 0

Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26671

This code can help you:

user_contract = ['ZNZ6','TNZ6','ZBZ6']
data = [[1,2,3],[4,5,6],[7,8,9]]
dictionary = dict(zip(user_contract, data))
print(dictionary)

It creates a dictionary from the two lists and prints it:

python3 pyprog.py 
{'ZBZ6': [7, 8, 9], 'ZNZ6': [1, 2, 3], 'TNZ6': [4, 5, 6]}

Upvotes: 7

coder.in.me
coder.in.me

Reputation: 1068

You can use exec to evaluate expressions and assign to variables dynamically:

>>> names = ','.join(user_contract)
>>> exec('{:s} = {:s}'.format(names, str(data)))

Upvotes: 2

Related Questions