Michael Eisenberger
Michael Eisenberger

Reputation: 5

How to unpack variables from tuple and give them names from another tuple?

I have two tuples - one with the keys and another one with a collection of variables of different types (list, float64, int and array) generate with the help of the following formula from a dictionary:

keys, values = zip(*[(key, value) for (key, value) in data_dict.items()])

Now I would like to retrieve the variables from the list of values and give them names from the list of keys. How can I do that?

Upvotes: 0

Views: 88

Answers (2)

Moberg
Moberg

Reputation: 5503

If you want to create variables in the global scope from your dictionary, perhaps you could update it like this:

globals().update(data_dict)

without unpacking the dict.

I'm not sure if this is what you're looking for.

Upvotes: 0

Karl Barker
Karl Barker

Reputation: 11341

If it's really not possible to store your key/value pairs in a dict and serialise them to data file in that format, you can use exec to dynamically construct assignment statements

>>> key = 'foo_var'
>>> val = 'foo_val'
>>> exec('{key} = \'{val}\''.format(key=key, val=val))
>>> foo_var
'foo_val'

I'd explore the dict approach first though, in case that can work for you. There are lots of good reasons to avoid runtime code generation using exec and eval where possible.

Upvotes: 1

Related Questions