删除项目后重命名字典键的更好方法?
A better way to rename keys of a dictionary after deletion of an item?
我有一本正在使用的字典。我偶尔会从中删除值,然后必须返回并重命名键。我正在这样完成重命名:
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, but I cannot pop off the old key, as the old key/value pair are gone. And this 涉及重新格式化字典中的 int/floats。
改为使用列表。如果您的键是连续整数,那么引用元素无论如何都是相同的,并且您不必为重命名键而烦恼:
>>> 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'
>>>
如果你真的想坚持使用字典,你可以像这样做你想做的,这不需要创建一个临时字典(尽管它会创建一个临时列表):
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'}
我有一本正在使用的字典。我偶尔会从中删除值,然后必须返回并重命名键。我正在这样完成重命名:
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, but I cannot pop off the old key, as the old key/value pair are gone. And this 涉及重新格式化字典中的 int/floats。
改为使用列表。如果您的键是连续整数,那么引用元素无论如何都是相同的,并且您不必为重命名键而烦恼:
>>> 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'
>>>
如果你真的想坚持使用字典,你可以像这样做你想做的,这不需要创建一个临时字典(尽管它会创建一个临时列表):
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'}