3

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?

A1122
  • 1,324
  • 3
  • 15
  • 35
  • 5
    Use a dictionary for this: https://docs.python.org/3/tutorial/datastructures.html#dictionaries – idjaw Sep 15 '16 at 01:54
  • 2
    wonderful, thank you. – A1122 Sep 15 '16 at 01:58
  • 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 00:22

3 Answers3

6

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]}
Nikolay Fominyh
  • 8,946
  • 8
  • 66
  • 102
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
  • This is a really neat trick, I was just wondering how the efficiency of this compared with a pandas DataFrame? – J.Massey Mar 03 '21 at 18:02
2

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

>>> names = ','.join(user_contract)
>>> exec('{:s} = {:s}'.format(names, str(data)))
coder.in.me
  • 1,048
  • 9
  • 19
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]
René
  • 4,594
  • 5
  • 23
  • 52
twinlakes
  • 9,438
  • 6
  • 31
  • 42