Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming dictionaries

Tags:

python

I'd like to know if there is a more simple/pythonic way to trim the "size/length" of a dictionary in python. If I have a dict with 10 key-value-pairs(elements) and I'd like to restrict the size to be 5. Is deleting elements in a loop the best solution (order/identity does not matter)

def _trim_search_results(self):

    MAX_RESULTS = 5

    # a big dict
    results_to_be_trimmed = {result_1 ... result_n}

    # dict with length MAX_RESULTS
    trimmed_results = {}

    for index, key in enumerate(results_to_be_trimmed):
        if index == MAX_RESULTS:
            break
        else:
            trimmed_results[key] = results_to_be_trimmed[key]

    results_to_be_trimmed = trimmed_results

I think there must be a better solution ...

like image 580
user937284 Avatar asked Sep 13 '13 15:09

user937284


People also ask

What you mean by trimming?

to put into a neat or orderly condition by clipping, paring, pruning, etc.: to trim a hedge. to remove (something superfluous or dispensable) by or as if by cutting (often followed by off): to trim off loose threads from a ragged edge. to cut down, as to required size or shape: trim a budget; trim a piece of wood.

What is an example of trimming?

The trimming on something such as a piece of clothing is the decoration, for example along its edges, that is in a different colour or material. ... the lace trimming on her satin dress.

What is the noun form of trim?

noun. /trɪm/ /trɪm/ Idioms. ​[countable, usually singular] an act of cutting a small amount off something, especially hair.


2 Answers

You could try

d = dict(d.items()[:MAX_RESULTS])

In Python 3:

d = dict(list(d.items())[:MAX_RESULTS])
like image 150
arshajii Avatar answered Sep 19 '22 12:09

arshajii


You can use itertools.islice on dict.iteritems.

dict.iteritems() returns an iterator in py2.x, you can slice that iterator using itertools.islice and pass it to dict() to get the new dict.

Demo:

>>> from itertools import islice
>>> d = dict.fromkeys(range(10))
>>> dict(islice(d.iteritems(), 5))
{0: None, 1: None, 2: None, 3: None, 4: None}

Timings:

>>> d = dict.fromkeys(range(100))
>>> %timeit from itertools import islice;dict(islice(d.iteritems(), 10)) #winner
10000 loops, best of 3: 10.7 us per loop
>>> %timeit dict(d.items()[0: 10])
100000 loops, best of 3: 10.9 us per loop

>>> d = dict.fromkeys(range(10**5))
>>> %timeit from itertools import islice;dict(islice(d.iteritems(), 1000)) #winner
1000 loops, best of 3: 106 us per loop
>>> %timeit dict(d.items()[0: 1000])
100 loops, best of 3: 20 ms per loop
like image 28
Ashwini Chaudhary Avatar answered Sep 18 '22 12:09

Ashwini Chaudhary