dictionary - How do you get the first 3 elements in Python OrderedDict? -
how first 3 elements in python ordereddict?
also possible delete data dictionary.
for example: how first 3 elements in python ordereddict , delete rest of elements?
let's create simple ordereddict
:
>>> collections import ordereddict >>> od = ordereddict(enumerate("abcdefg")) >>> od ordereddict([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')])
to return first 3 keys, values or items respectively:
>>> list(od)[:3] [0, 1, 2] >>> list(od.values())[:3] ['a', 'b', 'c'] >>> list(od.items())[:3] [(0, 'a'), (1, 'b'), (2, 'c')]
to remove except first 3 items:
>>> while len(od) > 3: ... od.popitem() ... (6, 'g') (5, 'f') (4, 'e') (3, 'd') >>> od ordereddict([(0, 'a'), (1, 'b'), (2, 'c')])
Comments
Post a Comment