JayJay123
JayJay123

Reputation: 313

A better way to rename keys of a dictionary after deletion of an item?

I have a dictionary that I am using. I occasionally delete values from it and then have to go back through and rename the keys. I am accomplishing the renaming like so:

TestDic = {0: "Apple", 2: "Orange", 3: "Grape"}
print(TestDic)
TempDic = {}
i = 0
for Key, DictValue in TestDic.iteritems():
    TempDic[i] = DictValue
    i += 1
TestDic= TempDic
print(TestDic)

Outputs:

{0: 'Apple', 1: 'Orange', 2: 'Grape'}

Great. Now is there a better way? I saw this, but I cannot pop off the old key, as the old key/value pair are gone. And this deals with reformatting the int/floats in the dictionary.

Upvotes: 2

Views: 570

Answers (2)

martineau
martineau

Reputation: 123473

If you really want to stick with using a dictionary, you could do what you want like this, which doesn't require creating a temporary dictionary (although it does create a temporary list):

testdic = {0: "Apple", 1: "Blueberry", 2: "Orange", 3: "Grape"}
print(testdic)

delkey = 1  # key of item to delete
del testdic[delkey]
print(testdic)

# go through dict's items and renumber those affected by deletion
for key, value in testdic.iteritems():
    if key > delkey:   # decrement keys greater than the key deleted
        testdic[key-1] = value
        del testdic[key]

print(testdic)

Output:

{0: 'Apple', 1: 'Blueberry', 2: 'Orange', 3: 'Grape'}
{0: 'Apple', 2: 'Orange', 3: 'Grape'}
{0: 'Apple', 1: 'Orange', 2: 'Grape'}

Upvotes: 2

schesis
schesis

Reputation: 59148

Use a list instead. If your keys are sequential integers, referencing elements will be the same anyway, and you won't have to mess about renaming keys:

>>> data = ["Apple", "Gooseberry", "Orange", "Grape"]
>>> data[0]
'Apple'
>>> data[1]
'Gooseberry'
>>> data[2]
'Orange'
>>> data[3]
'Grape'
>>> data.remove("Gooseberry")
>>> data
['Apple', 'Orange', 'Grape']
>>> data[0]
'Apple'
>>> data[1]
'Orange'
>>> data[2]
'Grape'
>>> 

Upvotes: 3

Related Questions