Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset new keys to a dictionary

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?

like image 820
Z Xie Avatar asked Dec 15 '22 04:12

Z Xie


2 Answers

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)
like image 184
BPL Avatar answered Jan 01 '23 12:01

BPL


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()))}
like image 31
Tim Fuchs Avatar answered Jan 01 '23 14:01

Tim Fuchs