65

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

HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34
hernanavella
  • 5,462
  • 8
  • 47
  • 84
  • 7
    "the beginning" and "the end" have no meaning with Python dictionaries because their order is arbitrary. –  Feb 24 '15 at 19:28
  • 1
    What do you mean by "first three elements"? A `dict` has no inherent sense of key ordering. –  Feb 24 '15 at 19:28
  • are you sure you're not confusing dictionaries and lists? – Marcus Müller Feb 24 '15 at 19:29
  • 1
    I meant, the first three elements that would come up if you call the dict on your console.....Sometimes you do that, and if the dict is very long, you get a ton of data that clutters all your console space. – hernanavella Feb 24 '15 at 19:30
  • Again: `dict`s have no inherent order. –  Feb 24 '15 at 19:34
  • @hernanavella: But you can't control or predict what three elements those will be. If you mean you want to just show an arbitrary subset of the dict elements, you can do that, but you won't know ahead of time exactly which elements you'll be seeing. – BrenBarn Feb 24 '15 at 19:34
  • 5
    @iCodez I get that, but what if you just want to take a quick look at how the dict looks. – hernanavella Feb 24 '15 at 19:35
  • @BrenBarn Ok. How do you show say 3 or 4 dict elements ? – hernanavella Feb 24 '15 at 19:36
  • I want to know how this is a dictionary `{[1,2], [2, 3], [3, 4]}` – Jdeep Jul 13 '20 at 16:42
  • 2
    This is not a strange desire at all — I often have the situation where some calculation has returned a dictionary and I want to look inside it to make sure that it has the correct data and I haven't made a mistake. The order doesn't matter, I just want to see a sample of the data. This doesn't seem like it should be hard. I think the best answer is `list(my_dict.items())[:5]` – larapsodia Nov 30 '22 at 18:33

13 Answers13

63

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])
user4600699
  • 1,465
  • 11
  • 10
  • 1
    perhaps `dict(sorted(mydict.items()[:3])` – heltonbiker Feb 24 '15 at 19:38
  • 3
    well if the order does matter, yes. But as far as i understand author don't need that. He just wants elements that would be printed at the beginning when printing dictionary and that is exactly what it is – user4600699 Feb 24 '15 at 19:41
  • 2
    `.items()` is an iterator, convert it to a list first, or it ll raise an error when sliced. – user Feb 24 '15 at 19:41
  • @user5061: No, OP specified Python 2.7. – John Y Feb 24 '15 at 19:43
  • 1
    # user 5061 In python2 items returns list. In python3 you can use islice to slice your iterator. – user4600699 Feb 24 '15 at 19:44
  • Not so strange, if you are using Jupiter notebook, a long dictionary will be shown completely, or rather it could crash the session. There is a missing functionality there, like for data frames, it only shows the top and bottom for longer data frames. – DISC-O Jun 03 '23 at 12:44
17

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])
Michal
  • 171
  • 1
  • 4
8
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.

Cadoiz
  • 1,446
  • 21
  • 31
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
6

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

Neb
  • 2,270
  • 1
  • 12
  • 22
5

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

Little Bobby Tables
  • 5,261
  • 2
  • 39
  • 49
2

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.

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
2

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

Wassadamo
  • 1,176
  • 12
  • 32
1

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.

  • He states in his comments that he already knows that. He just needs a small sample of dict contents. – user Feb 24 '15 at 19:38
1
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

user566245
  • 4,011
  • 1
  • 30
  • 36
0

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
alejandro
  • 521
  • 8
  • 18
  • Pay attention that this gives you an `object` instead of a `dict`. Meaning after `head = pd.Series(d).head()`, this will not work: `for name,group in head`... but this will: `for name in head.keys(): # \n # group = head[name]` – Cadoiz Jul 09 '20 at 19:32
0

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]
Tingmi
  • 1
0

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.

Rav
  • 329
  • 3
  • 5
0
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
Deryc
  • 58
  • 5
  • 1. needs `''` around `a, b, c`. 2. for first two elements, it's `[:2]`. 3. `i` is a tuple. 4. why not an f-string? 5. `i, d[i]` isn't right, you'd need `i[0], i[1]`. But `for k, v… print(f"{k}: {v}")` would be better. – Jack Deeth Feb 06 '22 at 13:41
  • (@JackDeeth about #4, question is flagged python 2.7, a f-string wouldn't be right.) Was this code tried ? As was already mentionned, .items() returns a tuple. You either want .keys() instead or need to change the print statement... – tgrandje Feb 18 '22 at 08:56