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