简体   繁体   中英

How do I remove key values in a dictionary?

Python language.

I know how to remove keys in a dictionary, for example:

def remove_zeros(dict)
    dict = {'B': 0, 'C': 7, 'A': 1, 'D': 0, 'E': 5}
    del dict[5]
    return dict

I want to know how to remove all values with zero from the dictionary and then sort the keys alphabetically. Using the example above, I'd want to get ['A', 'C', 'E'] as a result, eliminating key values B and D completely.

To sort do I just use dict.sort() ?

Is there a special function I must use?

sorted(k for (k, v) in D.iteritems() if v)

Sometimes when you code you have to take a step back and try to go for your intent, rather than trying to do one specific thing and miss the entire big picture. In python you have this feature called list/dictionary comprehension, from which you can use to filter the input to get the results you desire. So you want to filter out all values in your dictionary that are 0, it's simply this:

{k, v for k, v in d.items() if v != 0}

Now, dictionaries are hash tables, by default they are not sortable, however there is a class that can help you with this in collections . Using the OrderedDict class to facilitate the sorting, the code will end up like this:

OrderedDict(sorted(((k, v) for k, v in d.items() if v != 0)), key=lambda t: t[0])

Also, it's highly inadvisable to name your variables with the same name as a builtin type or method, such as dict .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM