有一个字典参数:
{'channel': 'DIMENSION',
'day': 'DIMENSION',
'subscribersGained': 'METRIC',
'likes': 'METRIC',
'views': 'METRIC',
'subscribersLost': 'METRIC'}
我想做的是,如果value == 'DIMENSION'
将其名称更改为'element_n'
,其中n是键的位置。
所以我想要的输出是
{'element_1': 'DIMENSION',
'element_2': 'DIMENSION',
'subscribersGained': 'METRIC',
'likes': 'METRIC',
'views': 'METRIC',
'subscribersLost': 'METRIC'}
到目前为止,我做到了
for k,v in params.items():
if v == 'DIMENSION':
v=['element_{}'.format(i+1) for i in range(len(params.values()))]
但这并没有改变任何东西
您可以改为使用以下字典理解enumerate
来重新构建字典,以格式化具有相应索引的键:
{k if v != 'DIMENSION' else 'element_{}'.format(i):v for i,(k,v) in enumerate(d.items())}
{'element_0': 'DIMENSION',
'element_1': 'DIMENSION',
'likes': 'METRIC',
'subscribersGained': 'METRIC',
'subscribersLost': 'METRIC',
'views': 'METRIC'}
输入数据 -
d = {'channel': 'DIMENSION',
'day': 'DIMENSION',
'subscribersGained': 'METRIC',
'likes': 'METRIC',
'views': 'METRIC',
'subscribersLost': 'METRIC'}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句