Remove "First" Item From Python Dict

Question:

Good afternoon.

I’m sorry if my question may seem dumb or if it has already been posted (I looked for it but didn’t seem to find anything. If I’m wrong, please let me know: I’m new here and I may not be the best at searching for the correct questions).

I was wondering if it was possible to remove (pop) a generic item from a dictionary in python.
The idea came from the following exercise:

Write a function to find the sum of the VALUES in a given dictionary.

Obviously there are many ways to do it: summing dictionary.values(), creating a variable for the sum and iterate through the dict and updating it, etc.. But I was trying to solve it with recursion, with something like:

def total_sum(dictionary):
    if dictionary == {}:
        return 0 
    return dictionary.pop() + total_sum(dictionary) 

The problem with this idea is that we don’t know a priori which could be the "first" key of a dict since it’s unordered: if it was a list, the index 0 would have been used and it all would have worked.
Since I don’t care about the order in which the items are popped, it would be enough to have a way to delete any of the items (a "generic" item). Do you think something like this is possible or should I necessarily make use of some auxiliary variable, losing the whole point of the use of recursion, whose advantage would be a very concise and simple code?

I actually found the following solution, which though, as you can see, makes the code more complex and harder to read: I reckon it could still be interesting and useful if there was some built-in, simple and direct solution to that particular problem of removing the "first" item of a dict, although many "artificious", alternative solutions could be found.

def total_sum(dictionary):
    if dictionary == {}:
        return 0
    return dictionary.pop(list(dictionary.keys())[0]) + total_sum(dictionary)

I will let you here a simple example dictionary on which the function could be applied, if you want to make some simple tests.

ex_dict = {"milk":5, "eggs":2, "flour": 3}

Answers:

ex_dict.popitem()

it removes the last (most recently added) element from the dictionary

Answered By: K.Doruk

You can pop items from a dict, but it get’s destroyed in the process. If you want to find the sum of values in a dict, it’s probably easiest to just use a list comprehension.

sum([v for v in ex_dict.values()])
Answered By: jgrant

Instead of thinking in terms of popping values, a more pythonic approach (as far is recursion is pythonic here) is to use an iterator. You can turn the dict’s values into an iterator and use that for recursion. This will be memory efficient, and give you a very clean stopping condition for your recursion:

ex_dict = {"milk":5, "eggs":2, "flour": 3}

def sum_rec(it):
    if isinstance(it, dict):
        it = iter(it.values())
    try:
        v = next(it)
    except StopIteration:
        return 0
    return v + sum_rec(it)

sum_rec(ex_dict)
# 10

This doesn’t really answer the question about popping values, but that really shouldn’t be an option because you can’t destroy the input dict, and making a copy just to get the sum, as you noted in the comment, could be pretty expensive.

Using popitem() would be almost the same code. You would just catch a different exception and expect the tuple from the pop. (And of course understand you emptied the dict as a side effect):

ex_dict = {"milk":5, "eggs":2, "flour": 3}

def sum_rec(d):
    try:
        k,v = d.popitem()
    except KeyError:
        return 0
    return v + sum_rec(d)

sum_rec(ex_dict)
# 10
Answered By: Mark

We can use:

dict.pop('keyname')
Answered By: Walk
(k := next(iter(d)), d.pop(k))

will remove the leftmost (first) item (if it exists) from a dict object.

And if you want to remove the right most/recent value from the dict

d.popitem()
Answered By: Sudarshan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.