There is a dict params:
{'channel': 'DIMENSION',
'day': 'DIMENSION',
'subscribersGained': 'METRIC',
'likes': 'METRIC',
'views': 'METRIC',
'subscribersLost': 'METRIC'}
What I want to do is if value == 'DIMENSION'
, change its name to 'element_n'
, where n is the key's position.
So my desired output is
{'element_1': 'DIMENSION',
'element_2': 'DIMENSION',
'subscribersGained': 'METRIC',
'likes': 'METRIC',
'views': 'METRIC',
'subscribersLost': 'METRIC'}
So far I did it
for k,v in params.items():
if v == 'DIMENSION':
v=['element_{}'.format(i+1) for i in range(len(params.values()))]
But it doesn't change anything
You could instead build the dictionary anew with the following dictionary comprehension with enumerate
to format the key with the corresponding index:
{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'}
Input data -
d = {'channel': 'DIMENSION',
'day': 'DIMENSION',
'subscribersGained': 'METRIC',
'likes': 'METRIC',
'views': 'METRIC',
'subscribersLost': 'METRIC'}
You can do it with a one-liner:
{(v == 'DIMENSION' and 'element_{}'.format(i) or k):v for i, (k, v) in enumerate(d.items(), 1)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With