Brendan
Brendan

Reputation: 11

trouble reindexing python dictionary

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.

Upvotes: 0

Views: 104

Answers (3)

keepAlive
keepAlive

Reputation: 6665

Yet another approach

my_odict = dict(
    sorted(
        my_dict.items(),
        key=lambda item: int(item[0])
    )
)

Upvotes: -1

Timur Shtatland
Timur Shtatland

Reputation: 12465

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'}]

Upvotes: 2

Barmar
Barmar

Reputation: 782693

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

my_dict = dict(enumerate(my_dict.values()))

Upvotes: -1

Related Questions