Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the value of a key in dict in Python with its position?

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

like image 211
Anna Avatar asked Sep 17 '19 09:09

Anna


2 Answers

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'}
like image 165
yatu Avatar answered Sep 28 '22 19:09

yatu


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)}
like image 37
FabioL Avatar answered Sep 28 '22 18:09

FabioL