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]))?
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]))?
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}
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()})