madsthaks
madsthaks

Reputation: 2181

Python - Looking for a more efficient way to renumber the keys in my dictionary

Here is my current dictionary:

{0: [(1,1.0)],
1: [(132,1.0)],
2: [(2000,1.0)],
3: [(234,1.0)]}

Now, there are instances where I may have to drop on of these keys. Lets take 2 for example, the resulting dictionary would look like this:

{0: [(1,1.0)],
1: [(132,1.0)],
3: [(234,1.0)]}

Now, I want to renumber the keys so they are consistently increasing by 1:

{0: [(1,1.0)],
1: [(132,1.0)],
2: [(234,1.0)]}

My first thought was to loop through the dictionary and replace the keys but that doesn't seem like the most efficient path considering my actual dictionary has 2000 keys.

Is there a more efficient way?

Upvotes: 1

Views: 389

Answers (3)

mad_
mad_

Reputation: 8273

It might be worth a try might solve your issue with OrderedDict

from collections import OrderedDict
d={0: [(1,1.0)],
1: [(132,1.0)],
3: [(234,1.0)],
-1:[(234,1.0)]} # added out of order case

od =OrderedDict(sorted(d.items()))

dict(zip(range(len(od)),od.values()))

Output:

{0: [(234, 1.0)], 1: [(1, 1.0)], 2: [(132, 1.0)], 3: [(234, 1.0)]}

Upvotes: -2

nosklo
nosklo

Reputation: 222922

D = dict(enumerate(D[x] for x in sorted(D)))

But please use a list. It is indexed by number and renumbers automatically:

>>> L = [
...    [(1,1.0)],
...    [(132,1.0)],
...    [(2000,1.0)],
...    [(234,1.0)]
... ]
>>> del L[1]
>>> print(L)
[
    [(1,1.0)],
    [(2000,1.0)],
    [(234,1.0)]
]

You can convert your dict to a list using L = [D[x] for x in sorted(D)] And convert back to your dict format by using D = dict(enumerate(L))

So that can be a solution:

D = dict(enumerate(D[x] for x in sorted(D)))

But it is better to just use a list in first place.

Upvotes: 5

Elisha
Elisha

Reputation: 4951

>>> current = {0: [(1,1.0)],
...      1: [(132,1.0)],
...      3: [(234,1.0)]}

>>> new_dict = {}
>>> for i,key in enumerate(sorted(original.keys())):
...     new_dict[i] = a[key]

>>> new_dict
{0: [(1,1.0)],
 1: [(132,1.0)],
 2: [(234,1.0)]}

Upvotes: 0

Related Questions