我有一个字典
tag_list = [{'Key': 'backup', 'Value': 'true'},
{'Key': 'backup_daily', 'Value': '7'}]
我想将其转换为变量,例如:
tag_backup = 'true'
tag_backup_daily = '7'
有什么简单的方法吗?
如果不需要将其转换为变量,是否还有其他更好的方法直接引用这些键/值?
我最好要做的是按以下方式引用。
tag_list['backup'] = "true"
tag_list['backup_daily'] = "7"
由于@Lev Zakharov的回答,我做到了以下方法。
>>> new_list = {x['Key']: x['Value'] for x in tag_list}
>>> new_list['backup']
'true'
>>> new_list['backup_daily']
'7'
答案 0 :(得分:6)
您可以使用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
答案 1 :(得分:5)
使用简单的dict理解:
{x['Key']:x['Value'] for x in tag_list}
结果:
{'backup': 'true', 'backup_daily': '7'}
答案 2 :(得分:3)
您只需使用for
循环
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'}
您还可以使用map
和lambda
创建一个tuple
s的容器,然后使用其构造函数转换为dict
< / p>
In [178]: dict(map(lambda d: (d['Key'], d['Value']), tag_list))
Out[178]: {'backup': 'true', 'backup_daily': '7'}
请注意,由于dict
构造函数的存在,该过程要慢得多
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