Bill
Bill

Reputation: 2973

convert array with dict to variables

I have an array with dict

 tag_list = [{'Key': 'backup', 'Value': 'true'},
 {'Key': 'backup_daily', 'Value': '7'}]

I'd like to convert it to variables, such as:

tag_backup = 'true'
tag_backup_daily = '7'

Any easy way to do that?

If no need to convert it to variables, any other better way to reference these key/value directly?

The best I want to do is to reference as below ways.

tag_list['backup'] = "true"
tag_list['backup_daily'] = "7"

UPDATE #1

Thanks to @Lev Zakharov 's answer, I did with below ways.

>>> new_list = {x['Key']: x['Value'] for x in tag_list}
>>> new_list['backup']
'true'
>>> new_list['backup_daily']
'7'

Upvotes: 3

Views: 99

Answers (3)

aydow
aydow

Reputation: 3801

You just use a for loop

In [184]: def to_dict(tags):
     ...:     d = {}
     ...:     for t in tags:
     ...:         d[t['Key']] = t['Value']
     ...:     return d
     ...:

In [185]: to_dict(tag_list)
Out[185]: {'backup': 'true', 'backup_daily': '7'}

You could also use map and lambda to create a container of tuples and then convert to a dict with its constructor

In [178]: dict(map(lambda d: (d['Key'], d['Value']), tag_list))
Out[178]: {'backup': 'true', 'backup_daily': '7'}

Note, that this is a lot slower due to the dict constructor

In [207]: %timeit to_dict(tag_list)
The slowest run took 31.74 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 431 ns per loop

In [181]: %timeit {d['Key']: d['Value'] for d in tag_list}
The slowest run took 44.42 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 457 ns per loop

In [182]: %timeit dict(map(lambda d: (d['Key'], d['Value']), tag_list))
The slowest run took 7.72 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.21 µs per loop

Upvotes: 3

Austin
Austin

Reputation: 26039

You could use globals():

tag_list = [{'Key': 'backup', 'Value': 'true'},
 {'Key': 'backup_daily', 'Value': '7'}]

for x in tag_list:
    globals()[f"tag_{x['Key']}"] = x['Value']

print(tag_backup)  # true
print(tag_backup_daily)  # 7

Upvotes: 6

Lev Zakharov
Lev Zakharov

Reputation: 2427

Use simple dict comprehension:

{x['Key']:x['Value'] for x in tag_list}

Result:

{'backup': 'true', 'backup_daily': '7'}

Upvotes: 5

Related Questions