0

I have a simple dictionary I deleted an index entry in the middle. I'm having trouble re-ordering my_dict index keys to be in sequence after I deleted an entry in the middle.

my_dict = {
    0: {
        "item_one": "a",
        "item_two": "b",

    },
    1: {
        "item_one": "c",
        "item_two": "d",

    },
    2: {
        "item_one": "e",
        "item_two": "f",

    }
}

del my_dict[1]

my_dict = {
    0: {
        "item_one": "a",
        "item_two": "b",

    },
    2: {
        "item_one": "e",
        "item_two": "f",
    }
}


I'm trying to loop through my_dict to change the keys to be in sequence from (0, 1, ...) instead of (0, 2, ...).

I was using the .keys() method to loop through my_dict and try and changes keys to reorder the dictionary keys to be in sequence but having trouble.

Brendan
  • 11
  • 3

3 Answers3

2

Use lists instead of dictionaries, as Iain Shelvington suggested in the comment. This is the correct data structure when you need to iterate by an integer, consecutive index. You can slice and dice it using del, pop, list slice and list comprehension.

my_dict = {
    "0": {
        "item_one": "a",
        "item_two": "b",  
    },
    "1": {
        "item_one": "c",
        "item_two": "d",
    },
    "2": {
        "item_one": "e",
        "item_two": "f",
    }
}

lst = list(my_dict.values())
print(lst)
# [{'item_one': 'a', 'item_two': 'b'}, {'item_one': 'c', 'item_two': 'd'}, {'item_one': 'e', 'item_two': 'f'}]

# To delete a list element:

# use del:
del lst[1]
# or pop:
lst.pop(1)
# or list slices:
lst = lst[:1] + lst[2:]

# In any of the cases above:
print(lst)
# [{'item_one': 'a', 'item_two': 'b'}, {'item_one': 'e', 'item_two': 'f'}]
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • 1
    thxs! a bit more context, I'm taking user input from a tkinter listbox and saving it to a .json file for reuse when running the program again. I was trying to build a function that removes selected users inputs from the listbox if they choose. I was having trouble with structuring the data in a list and was using this nested dictionary instead but will give it another try. I'm still pretty new to python, thanks for the help :) – Brendan Apr 18 '23 at 03:34
-1

Use enumerate() to create new keys for the dictionary.

my_dict = dict(enumerate(my_dict.values()))
Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

Yet another approach

my_odict = dict(
    sorted(
        my_dict.items(),
        key=lambda item: int(item[0])
    )
)
keepAlive
  • 6,369
  • 5
  • 24
  • 39