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
asked Feb 24, 2015 at 19:27
hernanavellahernanavella
5,3628 gold badges43 silver badges82 bronze badges
9
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]]
answered Feb 24, 2015 at 19:36
5
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]]
answered Jun 21, 2019 at 8:52
MichalMichal
1211 silver badge4 bronze badges
3
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,03414 silver badges24 bronze badges
answered Feb 24, 2015 at 19:37
BrenBarnBrenBarn
232k35 gold badges396 silver badges375 bronze badges
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
answered Nov 14, 2018 at 15:55
NebNeb
2,2221 gold badge11 silver badges22 bronze badges
3
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
answered Feb 27, 2019 at 7:03
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
answered Nov 24, 2018 at 19:39
WassadamoWassadamo
9169 silver badges23 bronze badges
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. OrderedDict
s remember the order of the keys as you entered them.
answered Feb 24, 2015 at 19:35
1
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.
answered Feb 24, 2015 at 19:35
heltonbikerheltonbiker
25.5k21 gold badges135 silver badges237 bronze badges
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
answered Jun 10, 2020 at 22:35
alejandroalejandro
4716 silver badges18 bronze badges
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
answered Nov 26, 2020 at 11:33
user566245user566245
3,6341 gold badge29 silver badges35 bronze badges
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]
answered May 19, 2021 at 15:39
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.
answered Sep 9, 2021 at 10:38
RavRav
1392 silver badges3 bronze badges
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
answered Feb 6 at 3:03
DerycDeryc
485 bronze badges
2