You should definitely be using a list
for such a feature, which would handle that feature per design.
>>> for i in l:
... print(l.index(i), i)
...
(0, 'Charlie')
(1, 'Alan')
(2, 'Jake')
(3, 'Rose')
>>> del l[2]
>>> for i in l:
... print(l.index(i), i)
...
(0, 'Charlie')
(1, 'Alan')
(2, 'Rose')
But for the sake of answering your question here's a solution:
>>> def remove_key(d, del_key):
... new_dict = {}
... for key, val in d.items():
... if key < del_key:
... new_dict[key] = val
... elif key > del_key:
... new_dict[key-1] = val
... else: # key == del_key
... continue
... return new_dict
...
>>> transDict={0:"Charlie", 1:"Alan", 2:"Jake", 3:"Rose"}
>>> remove_key(transDict, 2)
{0: 'Charlie', 1: 'Alan', 2: 'Rose'}
What was wrong in your algorithm:
for _id in transDict.keys(int(delkey) + 1:):
transDict[_id] = transDict[(int(_id) + 1)]
it is that,
- you're using range syntax within argument of the
keys()
method. The right syntax is to use the []
operator, e.g. .keys()[2:]
,
- you're iterating through all the indexes starting at position
delkey+1
of your dictionary, discarding the two possibilities, and you're shifting all the following values by one:
- the keys are unlikely to be ordered (because of the
dict
's definition),
- the keys might be sparse, which is likely to happen after a few keys removal.
So to build the algorithm I suggested you, I'm building a new dictionary, and while copying keys from the first dictionary to the new one, I consider the three following cases:
- if the key is inferior to the key to be deleted, copy that element as is,
- if the key is equal to the key to be deleted, skip that element,
- if the key is superior to the key to be deleted, copy that element shifted by one to the left
Then you can assign that new dictionary to the old one.
HTH