GDI
GDI

Reputation: 687

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?

Upvotes: 4

Views: 5471

Answers (5)

nigel222
nigel222

Reputation: 8222

If you want ordering by creation as well as access by key, then you want an OrderedDict.

>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> d['Cat'] = 'cool'
>>> d['Dog'] = 'best'
>>> d['Fish'] = 'cold'
>>> d['Norwegian Blue'] = 'ex-parrot'
>>> d
OrderedDict([('Cat', 'cool'), ('Dog', 'best'), ('Fish', 'cold'), ('Norwegian Blue', 'ex-parrot')])
 >>> d.values()
odict_values(['cool', 'best', 'cold', 'ex-parrot'])
>>> d.keys()
odict_keys(['Cat', 'Dog', 'Fish', 'Norwegian Blue'])

You retain the ability to access the items as a sequence in the order that they were added, but you also have the fast access-by-key which a dict (hash) gives you. If you want "natural" sequence numbers you use enumerate as normal:

>>> for i,it in enumerate( d.items()): 
...   print( '%5d %15s %15s' % ( i,it[0], it[1]) )
... 
    0             Cat            cool
    1             Dog            best
    2            Fish            cold
    3  Norwegian Blue       ex-parrot
>>>

Upvotes: 0

janbrohl
janbrohl

Reputation: 2656

If you want to keep the same order of keys

A={0:'dog',1:'cat',3:'fly',4,'fish',6:'lizard'}
new_A=dict((i,A[k]) for i,k in enumerate(sorted(A.keys()))

Upvotes: 2

Muhammad Khattab
Muhammad Khattab

Reputation: 19

Dictionaries are not ordered. If your keys are incremental integers, you might as well use a list.

new_A = list(A.values())

Upvotes: 1

Tim Fuchs
Tim Fuchs

Reputation: 1191

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

Upvotes: 3

BPL
BPL

Reputation: 9863

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)

Upvotes: 6

Related Questions