S
S
Sidorenko-ml2022-03-05 23:07:52
css
Sidorenko-ml, 2022-03-05 23:07:52

How to rename a key in a dictionary using a for or while loop?

I'm trying to solve a problem related to cycles.

Dictionary given:

{'test': 'test_value', 'europe': 'eur', 'dollar': 'usd', 'ruble': 'rub'}

#Add to each key a number equal to the length of this key (example -> ). # To get a list of keys, use the . Here is my code (I want to write through a function):{'key': 'value'}{'key3': 'value'}
.keys()


Dict1 = {'test': 'test_value',  
              'europe': 'eur',  
              'dollar': 'usd',  
              'ruble': 'rub'}

def KeyLen(dict):
    for k in dict.keys():
        k = k + str(len(k))
        return k    
    return dict.keys()
print(KeyLen(Dict1))

If I write like this, I only get "test4" in response.
Can you please hint where to dig?
I kind of understand that I accept a dictionary, I have to return it later, but it doesn't work return dictinstead of return dict.keys().

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mr.n1cky, 2016-04-27
@Millerish

1) Everything works
2) There are no errors in the console
(Safari)
Clean the cache.

P
PavelMos, 2022-03-06
@Sidorenko-ml

Changing the value by key = changing the value
Changing the key = creating a new key, with or without deleting the old one. According to the task, as I understand it, the old one needs to be deleted

def KeyLen(d1):
    d2=d1.copy() #надо копировать один объект (словарь) в другой, т.к. если присвоить через =, то при измененении первого будет меняться и второй
    for k1 in d1.keys():
        k2=k1+str(len(k1))
        d2[k2]=d1[k1]
        del d2[k1]
    return (d2)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question