0

I have a dictionary of the form
{0: -1.0, 21: 2.23, 7: 7.1, 46: -12.0}.

How can I turn this into
{'p0': -1.0, 'p21': 2.23, 'p7': 7.1, 'p46': -12.0}

efficiently i.e:

without a for loop and something like dict[key[i]] = dict.pop("p"+str(key[i]))?

Red
  • 26,798
  • 7
  • 36
  • 58
JohnDoe122
  • 638
  • 9
  • 23
  • Do you want to modify the existing dictionary (e.g. if you have various references to it), or is it sufficient to construct a new dictionary? – alani Jun 20 '20 at 22:26
  • No reply yet to this question so I posted a reply on this assumption. – alani Jun 20 '20 at 22:45
  • The most efficient way to to create a *new dictionary* and in any case it always requires a loop of sorts... And what do you mean by *efficiently*? – juanpa.arrivillaga Jun 21 '20 at 01:45
  • Does this answer your question? [Rename a dictionary key](https://stackoverflow.com/questions/16475384/rename-a-dictionary-key) – Nicolas Gervais Dec 03 '20 at 14:37

2 Answers2

6

You can use a dictionary comprehension:

d = {0: -1.0, 21: 2.23, 7: 7.1, 46: -12.0}

d = {f"p{k}":v for k,v in d.items()}

print(d)

Output:

{'p0': -1.0, 'p21': 2.23, 'p7': 7.1, 'p46': -12.0}



Note that this will work too:

d = {f"p{k}":d[k] for k in d}
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
Red
  • 26,798
  • 7
  • 36
  • 58
0

The mention in the question of item assignment and pop suggests that you wish to modify the existing dictionary. Unfortunately, you can only use the methods available, and there is no method to rename a key. Rather than do repeated item assignment and pop, the other option is simply to clear the dictionary completely and update from a complete new dictionary containing the modified keys. For example:

d1 = d.copy()
d.clear()
d.update({"p" + str(k): v for k, v in d1.items()})
alani
  • 12,573
  • 2
  • 13
  • 23
  • string concatenation with the int to string conversion `"p" + str(k)` was slower than an f-string `f"p{k}"` when I tried it on my machine using python 3.8.3. – Alex Jadczak Jun 20 '20 at 23:14