0

Trying to get the key from a dictionary reference. I'm basically looping over a list which is essentially a path to get down into a dictionary. If a key doesn't exist I'm creating it, but I need to do something based on the name of the previous key. Is there a way to get that info or should I just store it as another variable and constantly overwrite it?

Here's my code:

for obj in noun_adj:  # loop noun/adj
    if obj:
        try:
            work_on = work_on[obj]  # Store it as a reference to work on
        except KeyError:  # If there isn't a key stored yet
            #  I need the current key of work_on here...
Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
jbflow
  • 473
  • 2
  • 15
  • 1
    You should show show more of code and data structure and what exactly you are trying to achieve. Maybe you just need to do your main work one level higher where would have access to the **two** deepest keys. – user2390182 Dec 08 '20 at 13:39
  • 2
    Well from what it sounds like, the easiest will be to add a `prev_obj = obj` after `work_on` – Tomerikoo Dec 08 '20 at 13:52
  • Does this answer your question? [Iterate a list as pair (current, next) in Python](https://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python) – Tomerikoo Dec 08 '20 at 13:58
  • Yeah, this is probably what I will end up doing. Thanks will look at that question, holding the previous key somehow seems to be the best option. – jbflow Dec 08 '20 at 16:24

0 Answers0