删除项目后重命名字典键的更好方法是什么?

时间:2015-02-11 02:01:10

标签: python dictionary data-structures rename

我有一本我正在使用的字典。我偶尔会从中删除值,然后必须返回并重命名键。我正在完成重命名:

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)

输出:

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

大。现在有更好的方法吗?我看到了this,但我无法弹出旧密钥,因为旧密钥/值对已经消失。 this处理重新格式化字典中的int /浮点数。

2 个答案:

答案 0 :(得分:3)

请改用列表。如果你的键是连续的整数,那么引用元素无论如何都是相同的,你不必为重命名键而烦恼:

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

答案 1 :(得分:2)

如果你真的想坚持使用字典,你可以做你想要的事情,这不需要创建一个临时字典(虽然它确实创建了一个临时列表):

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)

输出:

{0: 'Apple', 1: 'Blueberry', 2: 'Orange', 3: 'Grape'}
{0: 'Apple', 2: 'Orange', 3: 'Grape'}
{0: 'Apple', 1: 'Orange', 2: 'Grape'}
相关问题