Python dictionary length truncation

Given an ordered Python dictionary, what is the most pythonic way to truncate its length? For example, if I am given a dictionary with several thousand entries, how do I truncate it only to the first 500 entries.

+4
source share
1 answer

Are you sure you want to change the dictionary in place? You can easily create a new one (thanks to iterators, without even touching objects that you don't need):

OrderedDict(itertools.islice(d.iteritems(), 500)) 

You can also trim the original one, but that would be less effective for the big one and would probably not be necessary. The semantics are different if someone uses d , of course.

 # can't use .iteritems() as you can't/shouldn't modify something while iterating it to_remove = d.keys()[500:] # slice off first 500 keys for key in to_remove: del d[key] 
+9
source

Source: https://habr.com/ru/post/1340455/


All Articles