在Python中,如何获取dict的部分视图?

2024-04-26 04:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有可能得到Python中类似熊猫的部分视图。假设有一个很长的dict,您只想检查dict的一些元素(开始、结束等)。类似于:

dict.head(3)  # To see the first 3 elements of the dictionary.

{[1,2], [2, 3], [3, 4]}

谢谢


Tags: oftheto视图元素dictionaryelementshead
3条回答

有点变态的欲望,但你可以用这个

dict(islice(mydict.iteritems(), 0, 2))

或是简短的字典

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

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

我知道这个问题有3年的历史了,但是这里有一个pythonic版本(可能比上面的方法简单)用于Python 3.*

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

它将打印字典的第一个n元素my_dict

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}

注意,插入一个新元素以一种不可预知的方式改变了“前”三个元素的内容。这就是人们告诉你听写是不听写的意思。如果你想的话,你可以得到三个元素,但是你不知道它们是哪三个。

相关问题 更多 >