Remove "First" Item From Python Dict
Asked Answered
S

7

7

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}
Sacred answered 20/7, 2020 at 14:12 Comment(4)
A larger problem with this is that you destroy the dictionary in the process. That’s unacceptable most of the time.Twicetold
Yeah, but you can avoid that by passing to the function a copy of the dict you're really interested in. The new problem now would be that in a context of big dimensions (Data Science etc.) it could be quite unefficient. Anyway, that was much more of a curiosity, and anyway this specific function was a bit of an "excuse" to highlight the more "generic" problem of finding a function with the same features as "pop", but that can pop the first item even without knowing its key.Sacred
@Twicetold in many algorithms, destructive iteration is both useful and perfectly acceptable. Keeping track of depth-first iterations, for example, where a dict keeps track of nodes that must be processed. When the dict becomes empty, iteration is complete.Casemate
@KenWilliams sure, that may be needed is some situations. However, a function whose job it is to provide the sum of a collection that also destroys that collection for no reason is still unacceptable. Most of the time mutating input arguments when that is not the specific function's job is a surprise to the caller. This isn't so much about destructive iteration as it is about functions and their contract with the caller.Twicetold
M
3

ex_dict.popitem()

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

Metal answered 20/7, 2020 at 14:15 Comment(4)
Correct. It returns a tuple (key, value). So to let the function work, you should refer to the second element of the tuple: return dictionary.popitem()[1] + total_sum(dictionary)Ascariasis
Thank you. It was giving me an error at first because, differently from "pop", it returns the whole couple key/value in a tuple, and I was using it exactly like pop which instead returns only the value. Now it all works just fine!Sacred
The answer misleading state that popitem() returns the first element. According to doc: Pairs are returned in LIFO (last-in, first-out) order. More over this is correct only from the Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.Airlee
@EgorBEremeev I've corrected this error in the answer.Casemate
E
13
(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()
Endopeptidase answered 7/6, 2022 at 16:37 Comment(1)
I think this answer more accurately answer the asked question, especially the clause: The problem with this idea is that we don't know a priori which could be the "first" key of a dictElviselvish
M
3

ex_dict.popitem()

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

Metal answered 20/7, 2020 at 14:15 Comment(4)
Correct. It returns a tuple (key, value). So to let the function work, you should refer to the second element of the tuple: return dictionary.popitem()[1] + total_sum(dictionary)Ascariasis
Thank you. It was giving me an error at first because, differently from "pop", it returns the whole couple key/value in a tuple, and I was using it exactly like pop which instead returns only the value. Now it all works just fine!Sacred
The answer misleading state that popitem() returns the first element. According to doc: Pairs are returned in LIFO (last-in, first-out) order. More over this is correct only from the Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.Airlee
@EgorBEremeev I've corrected this error in the answer.Casemate
S
3

I don't have enough reputation to comment on Sudarshan's comment so I'm just making my own post

The code he posted suffices

(k := next(iter(d)), d.pop(k))

But functionally does the same thing as

d.pop(next(iter(d)))

I think his implementation of next(iter(d)) was very clever though.

Soracco answered 7/3 at 1:13 Comment(0)
N
0

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()])
Noonday answered 20/7, 2020 at 14:19 Comment(1)
Thank you for the answer, but as I was saying to Mark in the comments, it was more like a curiosity about the possibility of a "default behaviour" for "pop", that makes it get the first item by default even without knowing the key. The particular context of the sum of the values, here, is kind of intened as a background information to contextualize the problem and provide a practical example.Sacred
T
0

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
Twicetold answered 20/7, 2020 at 14:27 Comment(0)
H
0

Since dict is ordered, this is one of the rare occasions where OrderedDict still is useful. It has like dict (see Sudarshan answer) the method popitem, but has additional the parameter last which return the first item if switched to False.

So you can either directly create a OrderedDict:

ex_dict = OrderedDict(milk=5, eggs=2, flour=3)
ex_dict.popitem(last=False)

or convert a given dict:

ex_odict = OrderedDict(**ex_dict)
ex_odict.popitem(last=False)



BTW the Answer of Alexei Pelyushenko is wrong! There is a quite important difference:

(k := next(iter(d)), d.pop(k))

returns the whole item as tuple of key and value ('milk', 5)
(same as ex_odict.popitem(last=False))

d.pop(next(iter(d)))

returns just the value 5

Headsman answered 25/7 at 12:0 Comment(0)
D
-2

We can use following pop syntax:

ex_dict = {"key1":5, "key2":2, "key3": 3 "key4": 4, "key5": 5}

ex_dict.pop('key2')

ex_dict

O/P: {"key1":5, "key3": 3, "key4": 4, "key5": 5}

key name can be mentioned

Doodlebug answered 2/6, 2022 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.