简体   繁体   中英

How to save tuple value into variable dynamically in python?

I need to save list of tuples into a string variable dynamically. Can you please help me?

Example:

lst = [('kol_id', '101152'), ('jnj_id', '7124166'), ('thrc_nm', 'VIR')]

Desirable output:

input_v1 = ('kol_id', '101152')
input_v2 = ('jnj_id', '7124166')
input_v3 = ('thrc_nm', 'VIR')

You can just save it in a dictionary.

lst = [('kol_id', '101152'), ('jnj_id', '7124166'), ('thrc_nm', 'VIR')]

d = {}

for i, element in enumerate(lst, 1):
    d[f'input_v{i}'] = element

so d is:

{'input_v1': ('kol_id', '101152'), 'input_v2': ('jnj_id', '7124166'), 'input_v3': ('thrc_nm', 'VIR')}

Inspired from @baduker's idea tried out using exec()

>>> lst = [('kol_id', '101152'), ('jnj_id', '7124166'), ('thrc_nm', 'VIR')]
>>> for i,val in enumerate(lst):
...     exec('input_v{} = {}'.format(i+1,val))
>>> input_v1
('kol_id', '101152')
>>> input_v2
('jnj_id', '7124166')
>>> input_v3
('thrc_nm', 'VIR')

exec() will execute for you whatever passed in string to it.

Try this:

lst = [('kol_id', '101152'), ('jnj_id', '7124166'), ('thrc_nm', 'VIR')]
def get_values(l):
    for idx, item in enumerate(l, start=1):
        yield f"input_v{idx} = {item}"
    
for _input in get_values(lst):
    print(_input)

This prints out:

input_v1 = ('kol_id', '101152')
input_v2 = ('jnj_id', '7124166')
input_v3 = ('thrc_nm', 'VIR')

I don't recommend saving your list of tuples to multiple variables.

It would be more scalable to put your tuples into one data structure, like a dictionary:

>>> lst = [('kol_id', '101152'), ('jnj_id', '7124166'), ('thrc_nm', 'VIR')]
>>> dic = {f"input_v{index}": tup for index, tup, in enumerate(lst, start=1)}
>>> dic
{'input_v1': ('kol_id', '101152'), 'input_v2': ('jnj_id', '7124166'), 'input_v3': ('thrc_nm', 'VIR')}
>>> dic['input_v1']
('kol_id', '101152')
>>> dic['input_v2']
('jnj_id', '7124166')
>>> dic['input_v3']
('thrc_nm', 'VIR')

If I understood question

lst = [('kol_id', '101152'), ('jnj_id', '7124166'), ('thrc_nm', 'VIR')]

for i, val in enumerate(lst):
    globals()[f'input_v{i + 1}'] = val # using f-string, python 3.6+

>>> input_v1
('kol_id', '101152')
>>> input_v2
('jnj_id', '7124166')
>>> input_v3
('thrc_nm', 'VIR')

But I'm think something wrong. I'm prefer dict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM