0

I have a dictionary, loaded from JSON, like so:

data = {
    "1": [
        "data",
        "data"
    ],
    "2": [
        "data",
        "data"
    ],
    "3": [
        "data",
        "data"
    ]
    "5": [
        "data",
        "data"
    ]
}

In this instance, "4" is missing, since it has been deleted through another function.

I am trying to write a function that will re-organize/sort the dictionary. This involves fixing holes such as this. In this instance, the numbers should go from 1 to 4 with no holes, this means changing the key-name 5 to 4.

I have written some code to find out which number is missing:

nums = [1, 2, 3, 5]
missing= 0
for x in range(len(data)):
    if x not in nums and x is not 0:
        missing += x

Greatly appreciate some help. I am simply stuck on how to proceed.

PS: I realize it may not be an optimal data structure. It is like this so I can easily match integers given as system arguments to keys and thus finding corresponding values.

So I just figured out a very easy way of doing it... was a lot simpler than I thought it would be.

for x in range(len(data)):
    for k, v in data.items():
        data[x] = data.pop(k)
        break
rpanai
  • 12,515
  • 2
  • 42
  • 64
Sebastian
  • 47
  • 1
  • 9
  • Your question has been answered in [Sort dictionary by key](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – tyncho08 Feb 27 '19 at 14:47
  • Thank you for your direction -- however, I realize I might have mis-titled my post. I don't meant to explicitly sort the dictionary, but to alter key-names so that they are sorted. – Sebastian Feb 27 '19 at 14:49
  • There's no such thing as changing keys in a dict. You'll have to create a new entry with the desired key and then delete the old one. – glibdud Feb 27 '19 at 14:54

1 Answers1

0

You could use enumerate to get the new indices for the existing (sorted) keys:

>>> data = {"1": ["data11", "data12"],
...         "2": ["data21", "data22"],
...         "3": ["data31", "data32"],
...         "5": ["data51", "data52"]}
...
>>> {i: data[k] for i, k in enumerate(sorted(data), start=1)}
{1: ['data11', 'data12'],
 2: ['data21', 'data22'],
 3: ['data31', 'data32'],
 4: ['data51', 'data52']}

Or the same, in-place (the if i != k: is not really needed, but might be faster):

>>> for i, k in enumerate(sorted(data), start=1):
...     if i != k:
...         data[i] = data.pop(k)
...
>>> data
{1: ['data11', 'data12'],
 2: ['data21', 'data22'],
 3: ['data31', 'data32'],
 4: ['data51', 'data52']}
tobias_k
  • 81,265
  • 12
  • 120
  • 179