Jen
Jen

Reputation: 27

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), what do I do? How would I go about doing so? I was hoping it would let me just slice (such as one does with lists), but I've been made aware that that's impossible.

EDIT: By index I mean indices. So for example, were I to remove the items from 1 to 3 of the sorted dictionary below, after it was sorted by value, then I would only be left with "eggs". EDIT 2: How do I find the keys in those places then (in indices 0, 1, 2)? EDIT 3: I'm not allowed to import or print in this.

For example:

>>>food = {"ham":12, "cookie":5, "eggs":16, "steak":2}
>>>remove_3(food)
{"eggs":16}

Upvotes: 0

Views: 8056

Answers (3)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

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

Upvotes: 0

ettanany
ettanany

Reputation: 19806

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 in list(ordered_dict)[:3]:
    del ordered_dict[key]

Output:

>>> ordered_dict
OrderedDict([('eggs', 16)])

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36023

Get key value pairs (.items()), sort them by value (item[1]), and take the first 3 ([:3]):

for key, value in sorted(food.items(), key=lambda item: item[1])[:3]:
    del food[key]

Upvotes: 2

Related Questions