Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python how to obtain a partial view of a dict?

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

like image 395
hernanavella Avatar asked Feb 24 '15 19:02

hernanavella


People also ask

Can you take a slice of a dictionary in Python?

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.

How do I fetch and display only the keys in a dictionary Python?

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.


1 Answers

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]) 
like image 146
Retard Avatar answered Sep 26 '22 00:09

Retard