从 Python Dict 中删除“ 第一” 项目
原标题:Remove "First" Item From Python Dict
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}
最佳回答
ex_dict.popitem()
it removes the last (most recently added) element from the dictionary
问题回答
(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()
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.
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()])
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
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
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