Removing Items Of A Certain Index From A Dictionary?
If I've got a dictionary and it's sorted, and I want to remove the first three items (in order of value) from it by index (no matter what the contents of the initial dictionary was
Solution 1:
Get key value pairs (.items()
), sort them by value (item[1]
), and take the first 3 ([:3]
):
forkey, valueinsorted(food.items(), key=lambda item: item[1])[:3]:
delfood[key]
Solution 2:
Try the following:
import operator
from collections import OrderedDict
food = {"ham": 12, "cookie": 5, "eggs": 16, "steak": 2}
ordered_dict = OrderedDict(sorted(food.items(), key=operator.itemgetter(1)))
for key inlist(ordered_dict)[:3]:
del ordered_dict[key]
Output:
>>> ordered_dict
OrderedDict([('eggs', 16)])
Solution 3:
Firstly, regarding your statement:
If I've got a dictionary and it's sorted
dict
in Python are not ordered in nature. Hence you can not preserve the order. If you want to create a dict
with the sorted order, use collections.OrderedDict()
. For example:
>>>from collections import OrderedDict>>>from operator import itemgetter>>>food = {"ham":12, "cookie":5, "eggs":16, "steak":2}>>>my_ordered_dict = OrderedDict(sorted(food.items(), key=itemgetter(1)))
The value hold by my_ordered_dict
will be:
>>> my_ordered_dict
OrderedDict([('steak', 2), ('cookie', 5), ('ham', 12), ('eggs', 16)])
which is equivalent to dict
preserving the order as:
{
'steak': 2,
'cookie': 5,
'ham': 12,
'eggs': 16
}
In order to convert the dict
excluding items with top 3 value, you have to slice the items (dict.items()
returns list of tuples in the form (key, value)
):
>>> dict(my_ordered_dict.items()[3:]) # OR, OrderedDict(my_ordered_dict.items()[3:])
{'eggs': 16} # for maintaining the order
Post a Comment for "Removing Items Of A Certain Index From A Dictionary?"