Slicing is available for lists in python
list1 =[1,2,3,4,5,6]
list1[:3]
[1, 2, 3]
Similarly, slicing or anything similar to that available for dictionary ?
dict1 = {1":a",2:"b",3:"c",4:"d",5:"e"}
I would like to get any 3 (can be random) elements of dictionary, just providing the number (as provided above for list [:2]
), then i should be getting below dictionary
dict1 = {1":a",2:"b"} # After slicing
How can this dictionary slicing or alternative be achieved in python
& Robot-framework
?
Maybe this is a solution you could consider, since a dict
can not be accessed as a list
:
dict1 = {1:"a",2:"b",3:"c",4:"d",5:"e"}
def take(dct, high=None, low=None):
return dict(list(dct.items())[low:high])
print(take(dict1, 3)) #=> {1: 'a', 2: 'b', 3: 'c'}
print(take(dict1, 5, 2)) #=> {3: 'c', 4: 'd', 5: 'e'}