5

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?

3

3 Answers 3

7

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]}
Sign up to request clarification or add additional context in comments.

1 Comment

This is a really neat trick, I was just wondering how the efficiency of this compared with a pandas DataFrame?
3

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

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

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.