简体   繁体   中英

Truncate the length of a Python dictionary

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

Do you really to modify the dictionary in-place? You can easily generate a new one (thanks to iterators, without even touching the items you don't need):

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

You could also truncate the original one, but that would be less performant for large one and is propably not needed. Semantics are different if someone else is using 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]

If the dict is already ordered you can just select the number of elements you need like this

dict = json.loads(response.text)
dicts_result = dict['results']

dicts_result = dicts_result[:5] #This gives me 5 elements

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