Python 如何获取字典的部分视图?
In Python how to obtain a partial view of a dict?
是否可以在 Python 中获取类似于 pandas df.tail()/df.head()
的 dict
的部分视图。假设您有一个很长的 dict
,而您只想检查 dict
的一些元素(开头、结尾等)。类似于:
dict.head(3) # To see the first 3 elements of the dictionary.
{[1,2], [2, 3], [3, 4]}
谢谢
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.
我最多只是玩弄其他 Python 实现(例如 PyPy、IronPython 等),所以我不确定是否全部都是这种情况Python 实现,但是 dict/hashmap/hash/etc 的一般思想是键是无序的。
也就是说,您可以使用 OrderedDict
from the collections
library。 OrderedDict
记住您输入按键的顺序。
如果键可以排序,您可以这样做:
head = dict([(key, myDict[key]) for key in sorted(myDict.keys())[:3]])
或者也许:
head = dict(sorted(mydict.items(), key=lambda: x:x[0])[:3])
其中 x[0]
是每个 key/value 对的键。
有点奇怪的愿望,但你可以通过使用这个
from itertools import islice
# Python 2.x
dict(islice(mydict.iteritems(), 0, 2))
# Python 3.x
dict(islice(mydict.items(), 0, 2))
或短字典
# Python 2.x
dict(mydict.items()[0:2])
# Python 3.x
dict(list(mydict.items())[0:2])
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}
但是:
>>> x['a'] = 2
>>> glance(x)
{1: 2, 3: 4, u'a': 2}
请注意,插入新元素以不可预知的方式改变了“前”三个元素的内容。这就是人们告诉你口述没有顺序的意思。如果你愿意,你可以得到三个元素,但你无法知道它们将是哪三个。
我知道这个问题已经有 3 年了,但是这里有一个 pythonic 版本(可能比上面的方法更简单)Python 3.*
:
[print(v) for i, v in enumerate(my_dict.items()) if i < n]
它将打印字典的前 n
个元素 my_dict
对于那些宁愿使用 pandas
数据帧解决此问题的人。只需将您的字典 mydict
填充到数据框中,旋转它,并获取前几行:
pd.DataFrame(mydict, index=[0]).T.head()
0 hi0
1 hi1
2 hi2
3 hi3
4 hi4
使用Python 3 字典理解的@Neb 解决方案:
{k: v for i, (k, v) in enumerate(my_dict.items()) if i < n}
它returns是一个口述而不是打印输出
编辑:
在Python3.x中:
在不使用库的情况下,可以这样做。使用方法:
.items()
其中 returns 具有值的字典键列表。
需要转为列表,否则会出错'my_dict'对象不可订阅。然后将其转换为字典。现在可以用方括号切片了。
dict(list(my_dict.items())[:3])
一个快速而简短的解决方案可以是这样的:
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
list(reverse_word_index.items())[:10]
将数字从 10 更改为您要预览的字典中的任何项目reverse_word_index
这返回一个字典:
dict(list(my_dictname.items())[0:n])
如果你只是想看一眼你的字典,那么就这样做:
list(freqs.items())[0:n]
字典中项目的顺序在 Python 3.7+ 中保留,所以这个问题是有道理的。
要从一开始就得到只有 10 个项目的字典,您可以使用 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)
这将生成一个新词典。
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
是否可以在 Python 中获取类似于 pandas df.tail()/df.head()
的 dict
的部分视图。假设您有一个很长的 dict
,而您只想检查 dict
的一些元素(开头、结尾等)。类似于:
dict.head(3) # To see the first 3 elements of the dictionary.
{[1,2], [2, 3], [3, 4]}
谢谢
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.
我最多只是玩弄其他 Python 实现(例如 PyPy、IronPython 等),所以我不确定是否全部都是这种情况Python 实现,但是 dict/hashmap/hash/etc 的一般思想是键是无序的。
也就是说,您可以使用 OrderedDict
from the collections
library。 OrderedDict
记住您输入按键的顺序。
如果键可以排序,您可以这样做:
head = dict([(key, myDict[key]) for key in sorted(myDict.keys())[:3]])
或者也许:
head = dict(sorted(mydict.items(), key=lambda: x:x[0])[:3])
其中 x[0]
是每个 key/value 对的键。
有点奇怪的愿望,但你可以通过使用这个
from itertools import islice
# Python 2.x
dict(islice(mydict.iteritems(), 0, 2))
# Python 3.x
dict(islice(mydict.items(), 0, 2))
或短字典
# Python 2.x
dict(mydict.items()[0:2])
# Python 3.x
dict(list(mydict.items())[0:2])
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}
但是:
>>> x['a'] = 2
>>> glance(x)
{1: 2, 3: 4, u'a': 2}
请注意,插入新元素以不可预知的方式改变了“前”三个元素的内容。这就是人们告诉你口述没有顺序的意思。如果你愿意,你可以得到三个元素,但你无法知道它们将是哪三个。
我知道这个问题已经有 3 年了,但是这里有一个 pythonic 版本(可能比上面的方法更简单)Python 3.*
:
[print(v) for i, v in enumerate(my_dict.items()) if i < n]
它将打印字典的前 n
个元素 my_dict
对于那些宁愿使用 pandas
数据帧解决此问题的人。只需将您的字典 mydict
填充到数据框中,旋转它,并获取前几行:
pd.DataFrame(mydict, index=[0]).T.head()
0 hi0
1 hi1
2 hi2
3 hi3
4 hi4
使用Python 3 字典理解的@Neb 解决方案:
{k: v for i, (k, v) in enumerate(my_dict.items()) if i < n}
它returns是一个口述而不是打印输出
编辑:
在Python3.x中: 在不使用库的情况下,可以这样做。使用方法:
.items()
其中 returns 具有值的字典键列表。
需要转为列表,否则会出错'my_dict'对象不可订阅。然后将其转换为字典。现在可以用方括号切片了。
dict(list(my_dict.items())[:3])
一个快速而简短的解决方案可以是这样的:
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
list(reverse_word_index.items())[:10]
将数字从 10 更改为您要预览的字典中的任何项目reverse_word_index
这返回一个字典:
dict(list(my_dictname.items())[0:n])
如果你只是想看一眼你的字典,那么就这样做:
list(freqs.items())[0:n]
字典中项目的顺序在 Python 3.7+ 中保留,所以这个问题是有道理的。
要从一开始就得到只有 10 个项目的字典,您可以使用 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)
这将生成一个新词典。
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