Is it possible to get a partial view of a dict
in Python analogous of pandas df.tail()/df.head()
. Say you have a very long dict
, and you just want to check some of the elements (the beginning, the end, etc) of the dict
. Something like:
dict.head(3) # To see the first 3 elements of the dictionary. {[1,2], [2, 3], [3, 4]}
Thanks
With Python, we can easily slice a dictionary to get just the key/value pairs we want. To slice a dictionary, you can use dictionary comprehension. In Python, dictionaries are a collection of key/value pairs separated by commas.
The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Parameters: There are no parameters. Returns: A view object is returned that displays all the keys.
Kinda strange desire, but you can get that by using this
dict(islice(mydict.iteritems(), 0, 2))
or for short dictionaries
# Python 2.x dict(mydict.items()[0:2]) # Python 3.x dict(list(mydict.items())[0:2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With