2

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.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
JayJay123
  • 315
  • 1
  • 5
  • 12

2 Answers2

3

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'
>>> 
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • I'm using variable variables and am kind of fully vested in using a dictionary--lots of code already. My little function works, but I was just wondering if there were a better way, if one were using a dictionary. If I rewrite down the road, I will look to use a list, but changing this far in is not possible. A dictionary may have been a bad choice, but I guess that is a bonus learn for me to use in the future. Thanks. – JayJay123 Feb 11 '15 at 02:22
  • 1
    What is a "variable variable"? – kindall Feb 11 '15 at 02:29
  • @JayJay123 If you mean what I think you mean by "variable variables", you might want to read [this](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html). – Zero Piraeus Feb 11 '15 at 02:44
  • 1
    @JayJay123 I have to admit I'm fascinated to know what you're up to with all these variable variables and dicts simulating lists ... care to join me in [chat](http://chat.stackoverflow.com/rooms/6/python)? – Zero Piraeus Feb 11 '15 at 02:49
2

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'}
martineau
  • 119,623
  • 25
  • 170
  • 301
  • A couple of minor nits – 1: `sorted()` has to convert `testdic.iteritems()` into a list before sorting it, so you might as well just use `testdic.items()` (in fact, it should be marginally faster), and 2: there's no need for `key=itemgetter(0)`: the tuples will be lexicographically sorted anyway. – Zero Piraeus Feb 11 '15 at 03:09
  • @Zero: You're correct about not needing to sort (or use `itemgetter` to do it), but only because the order doesn't matter (_not_ because the tuples will be sorted anyway -- they won't since dictionaries are unordered). – martineau Feb 11 '15 at 03:19
  • I think I must have expressed myself badly; I meant that if you *are* sorting, there's no need for `key=itemgetter(0)` because comparisons between tuples are lexicographic, and automatically compare `t[0]` before anything else. As it happens, because `hash(n) == n` for all positive integers, it's quite likely (but not guaranteed unless all the other code inserts items in the "right" order) that the dictionaries **are** going to be ordered "naturally", but that's really getting into minutiae. As you say, though, the sort isn't actually necessary, and all of this is nitpicking :-) – Zero Piraeus Feb 11 '15 at 03:33
  • Anyway, +1 for the "how to do it if you really want to do it" solution :-) – Zero Piraeus Feb 11 '15 at 03:35