开发者

Truncate the length of a Python dictionary

开发者 https://www.devze.com 2023-02-11 22:16 出处:网络
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

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 en开发者_高级运维tries 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
0

精彩评论

暂无评论...
验证码 换一张
取 消