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

PythonPython 2.7Dictionary

Python Problem Overview


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

Python Solutions


Solution 1 - Python

Kinda strange desire, but you can get that by using this

from itertools import islice

# Python 2.x
dict(islice(mydict.iteritems(), 0, 2))

# Python 3.x
dict(islice(mydict.items(), 0, 2))

or for short dictionaries

# Python 2.x
dict(mydict.items()[0:2])

# Python 3.x
dict(list(mydict.items())[0:2])

Solution 2 - Python

Edit:

in Python 3.x: Without using libraries it's possible to do it this way. Use method:

> .items()

which returns a list of dictionary keys with values.

It's necessary to convert it to a list otherwise an error will occur 'my_dict' object is not subscriptable. Then convert it to the dictionary. Now it's ready to slice with square brackets.

dict(list(my_dict.items())[:3])

Solution 3 - Python

import itertools 
def glance(d):
    return dict(itertools.islice(d.iteritems(), 3))

>>> x = {1:2, 3:4, 5:6, 7:8, 9:10, 11:12}
>>> glance(x)
{1: 2, 3: 4, 5: 6}

However:

>>> x['a'] = 2
>>> glance(x)
{1: 2, 3: 4, u'a': 2}

Notice that inserting a new element changed what the "first" three elements were in an unpredictable way. This is what people mean when they tell you dicts aren't ordered. You can get three elements if you want, but you can't know which three they'll be.

Solution 4 - Python

I know this question is 3 years old but here a pythonic version (maybe simpler than the above methods) for Python 3.*:

[print(v) for i, v in enumerate(my_dict.items()) if i < n]

It will print the first n elements of the dictionary my_dict

Solution 5 - Python

one-up-ing @Neb's solution with Python 3 dict comprehension:

{k: v for i, (k, v) in enumerate(my_dict.items()) if i < n}

It returns a dict rather than printouts

Solution 6 - Python

For those who would rather solve this problem with pandas dataframes. Just stuff your dictionary mydict into a dataframe, rotate it, and get the first few rows:

pd.DataFrame(mydict, index=[0]).T.head()

0 hi0 1 hi1 2 hi2 3 hi3 4 hi4

Solution 7 - Python

From the documentation:

> CPython implementation detail: Keys and values are listed in an > arbitrary order which is non-random, varies across Python > implementations, and depends on the dictionary’s history of insertions > and deletions.

I've only toyed around at best with other Python implementations (eg PyPy, IronPython, etc), so I don't know for certain if this is the case in all Python implementations, but the general idea of a dict/hashmap/hash/etc is that the keys are unordered.

That being said, you can use an OrderedDict from the collections library. OrderedDicts remember the order of the keys as you entered them.

Solution 8 - Python

If keys are someway sortable, you can do this:

head = dict([(key, myDict[key]) for key in sorted(myDict.keys())[:3]])

Or perhaps:

head = dict(sorted(mydict.items(), key=lambda: x:x[0])[:3])

Where x[0] is the key of each key/value pair.

Solution 9 - Python

A quick and short solution can be this:

import pandas as pd

d = {"a": [1,2], "b": [2, 3], "c": [3, 4]}

pd.Series(d).head()

a    [1, 2]
b    [2, 3]
c    [3, 4]
dtype: object

Solution 10 - Python

list(reverse_word_index.items())[:10]

Change the number from 10 to however many items of the dictionary reverse_word_index you want to preview

Solution 11 - Python

This gives back a dictionary:

dict(list(my_dictname.items())[0:n])

If you just want to have a glance of your dict, then just do:

list(freqs.items())[0:n]

Solution 12 - Python

Order of items in a dictionary is preserved in Python 3.7+, so this question makes sense.

To get a dictionary with only 10 items from the start you can use pandas:

d = {"a": [1,2], "b": [2, 3], "c": [3, 4]}

import pandas as pd
result = pd.Series(d).head(10).to_dict()
print(result)

This will produce a new dictionary.

Solution 13 - Python

d = {"a": 1,"b": 2,"c": 3}
for i in list(d.items())[:2]:
     print('{}:{}'.format(d[i][0], d[i][1]))

a:1
b:2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhernanavellaView Question on Stackoverflow
Solution 1 - PythonRetardView Answer on Stackoverflow
Solution 2 - PythonMichalView Answer on Stackoverflow
Solution 3 - PythonBrenBarnView Answer on Stackoverflow
Solution 4 - PythonNebView Answer on Stackoverflow
Solution 5 - PythonLittle Bobby TablesView Answer on Stackoverflow
Solution 6 - PythonWassadamoView Answer on Stackoverflow
Solution 7 - Pythonuser554546View Answer on Stackoverflow
Solution 8 - PythonheltonbikerView Answer on Stackoverflow
Solution 9 - PythonalejandroView Answer on Stackoverflow
Solution 10 - Pythonuser566245View Answer on Stackoverflow
Solution 11 - PythonTingmiView Answer on Stackoverflow
Solution 12 - PythonRavView Answer on Stackoverflow
Solution 13 - PythonDerycView Answer on Stackoverflow