Ad

How To Change The Value Of A Key In Dict In Python With Its Position?

- 1 answer

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

Ad

Answer

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'}
Ad
source: stackoverflow.com
Ad