I have a python dictionary.
A=[0:'dog',1:'cat',3:'fly',4,'fish',6:'lizard']
I want to reset the keys according to range(len(A))
(the natural increment), which should look like:
new_A=[0:'dog',1:'cat',2:'fly',3:'fish',4:'lizard']
How could I do that?
Here's a working example for both py2.x and py3.x:
A = {0: 'dog', 1: 'cat', 3: 'fly', 4: 'fish', 6: 'lizard'}
B = {i: v for i, v in enumerate(A.values())}
print(B)
If you want to assign new keys in the ascending order of old keys, then
new_A = {i: A[k] for i, k in enumerate(sorted(A.keys()))}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With