在 Python 中如何获取 dict 的局部视图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28704526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Python how to obtain a partial view of a dict?
提问by hernanavella
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
类似于 pandas 的 Python 中a 的部分视图df.tail()/df.head()
。假设您有一个很长的dict
,并且您只想检查dict
. 就像是:
dict.head(3) # To see the first 3 elements of the dictionary.
{[1,2], [2, 3], [3, 4]}
Thanks
谢谢
采纳答案by Retard
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])
回答by hernanavella
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.
CPython 实现细节:键和值以非随机的任意顺序列出,因 Python 实现而异,并取决于字典的插入和删除历史。
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.
我最多只玩弄过其他 Python 实现(例如 PyPy、IronPython 等),所以我不确定所有 Python 实现是否都是这种情况,但是 dict/hashmap/hash 的总体思路/etc 是键是无序的。
That being said, you can use an OrderedDict
from the collections
library. OrderedDict
s remember the order of the keys as you entered them.
话虽这么说,你可以使用OrderedDict
从collections
库。OrderedDict
记住您输入的键的顺序。
回答by heltonbiker
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.
x[0]
每个键/值对的键在哪里。
回答by BrenBarn
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.
请注意,插入一个新元素以不可预测的方式改变了“第一个”三个元素。这就是人们告诉您 dicts 没有排序时的意思。如果你愿意,你可以得到三个元素,但你不知道它们会是哪三个。
回答by Neb
I know this question is 3 years old but here a pythonic version (maybe simpler than the above methods) for Python 3.*
:
我知道这个问题已经有 3 年历史了,但这里有一个 pythonic 版本(可能比上述方法更简单)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
它将打印n
字典的第一个元素my_dict
回答by Wassadamo
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:
对于那些宁愿用pandas
数据框解决这个问题的人。只需将您的字典填充mydict
到数据框中,旋转它,然后获取前几行:
pd.DataFrame(mydict, index=[0]).T.head()
0 hi0
1 hi1
2 hi2
3 hi3
4 hi4
0 hi0
1 hi1
2 hi2
3 hi3
4 hi4
回答by Little Bobby Tables
one-up-ing @Neb's solution with Python 3 dict comprehension:
使用 Python 3 dict 理解的一对一@Neb 解决方案:
{k: v for i, (k, v) in enumerate(my_dict.items()) if i < n}
It returns a dict rather than printouts
它返回一个字典而不是打印输出
回答by Michal
Edit:
编辑:
in Python 3.x: Without using libraries it's possible to do it this way. Use method:
在 Python 3.x 中:不使用库就可以这样做。使用方法:
.items()
。项目()
which returns a list of dictionary keys with values.
它返回带有值的字典键列表。
It 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.
必须将其转换为列表,否则将发生错误 'my_dict' object is not subscriptable。然后将其转换为字典。现在可以用方括号切片了。
dict(list(my_dict.items())[:3])