When you first start the IPython block with a variable with a dictionary, for example:

In[7]: test_dict = {'key_1': 1.8529757571664867, 'key_2': 1.551270403313663, 'key_3': 0.8213399558579995} 

and function:

 In[8]: def rename_keys(inp_dict, add): for k, v in sorted(inp_dict.items()): inp_dict[k + add] = inp_dict.pop(k) return inp_dict In[9]: rename_keys(test_dict, '_W') 

IPython will print the expected result:

 Out[9]: {'key_1_W': 1.8529757571664867, 'key_2_W': 1.551270403313663, 'key_3_W': 0.8213399558579995} 

But, if for example I wanted to change the ending from "_W" to "_K", then when changing and re-running the block, I will get the old variable with the already changed ending + new ending:

 In[10]: rename_keys(test_dict, '_K') Out[10]: {'key_1_W_K': 1.8529757571664867, 'key_2_W_K': 1.551270403313663, 'key_3_W_K': 0.8213399558579995} 

How to make notepad run code from scratch?

UPD: Of course, it is logical and obvious that subsequent calls imply an object that has already been changed, but is it possible to make it so that if you change it in In[9] I would have output Out[9] ?

    1 answer 1

     # новый объект print({'%s_W' % k: test_dict[k] for k in test_dict}) print({'%s_K' % k: test_dict[k] for k in test_dict}) # Или, если возвращать тот же объект def rename_keys(inp_dict): dt = inp_dict.copy() while True: add = yield inp_dict.clear() inp_dict.update({k + add: dt[k] for k in dt}) yield inp_dict r = rename_keys(test_dict) next(r) print(r.send('_W')) next(r) print(r.send('_K')) 
    • +1 for the option that input - jfs