I tried searching for this an answer to this question for a long time now. I tried everywhere, but could be that I am searching with the wrong keywords, if so, please forgive me for asking a stupid or already answered question.
I am trying to pop a dictionary in python 2.2. The following is a snippet of my code that I am trying to run:
ABRA= {}
ABRA[0] = ['MENU', ['TV', 'MENU']]
ABRA[1] = ['TV', 'PC', ['RM', 'LM']]
count = 0
KADABRA = ABRA.pop(count).pop()
print(str(KADABRA))
print(len(KADABRA))
count += 1
KADABRA = ABRA.pop(count)
print(str(KADABRA))
When I enter this code in an online interpreter like Codepad, it works and I get the desired output, when I run it on the server where I would like it to run, it doesn't. I get the following error:
AttributeError ('dict' object has no attribute 'pop').
I don't see a mistake in the code, or in the way that I am calling the pop. I even tried to remove the 'double' pop. Still an error. If I just make it a list instead of a dict like this:
ABRA = ['MENU', ['TV', 'MENU']]
KADABRA = ABRA.pop()
print(str(KADABRA))
print(len(KADABRA))
Then it works and I get the right prints. But I don't want a list of lists, but a dict. I have seen examples of popping with dicts. So my question is why can't i pop the dict on my server and/or is there an alternative to popping with dicts?
From the dict.pop()
documentation:
New in version 2.3.
In other words, there is no such method in Python 2.2.
You can implement this yourself with:
_sentinel = object()
def pop_dict(d, k, default=_sentinel):
try:
v = d[k]
del d[k]
return v
except KeyError:
if default is _sentinel:
raise
return default
Use this as:
pod_dict(ABRA, count)