English 中文(简体)
从 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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签