在Python 3中对字典进行子集操作

3
如何使用Python 3子集合一个字典? 使用Python 2,以下内容有效:
global pair_dict

pair_dict = {
    1: 'one',
    2: 'two',
    3: 'three',
    4: 'four',
    5: 'five',
    6: 'six',
    7: 'seven',
    8: 'eight'
}


global test_printer

def test_printer(start_chunk, end_chunk):

    # .items() replacing .iteritems() from Python 2
    sub_dict = dict(pair_dict.items()[start_chunk:end_chunk])
    print sub_dict

test_printer(0, 2)

然而,在这个版本的Python中,我现在遇到了以下错误:

Traceback (most recent call last):
  File "G:/HTPC Scripts/WebGrab Plus/TESTTESTTEST2.py", line 52, in <module>
    set_chunk_start_end_points()
  File "G:/HTPC Scripts/WebGrab Plus/TESTTESTTEST2.py", line 48, in set_chunk_start_end_points
    test_printer(start_chunk, end_chunk)
  File "G:/HTPC Scripts/WebGrab Plus/TESTTESTTEST2.py", line 27, in test_printer
    sub_dict = dict(pair_dict.values()[start_chunk:end_chunk])
TypeError: 'dict_values' object is not subscriptable

期望的输出是什么?将字典返回的前两个项目放入子字典中? - Chris Doyle
嗨...将前两个键/值对放入子集中。1:'one',2:'two', - gdogg371
在我的实际代码中,我也有一个有序步骤...只是为了清晰起见,我将其省略了。 - gdogg371
1
根据您的Python版本,您不能保证返回的前两个项目是什么。如果您真的想这样做,您可以使用sub_dict = dict(list(pair_dict.items())[start_chunk:end_chunk]) - Chris Doyle
2个回答

3
你遇到的问题就像错误提示说的一样。特殊的'dict_values'对象是不可索引的。如果在尝试下标操作之前将 pair_dict.items() / pair_dict.values() 转换为列表,你将得到所需的结果。
在Python2中,这些方法返回一个列表对象而不是迭代器,所以可以正常工作。

谢谢。我不是全职的Python开发人员,我已经使用2.7版本很长时间了,忘记了很多与3.x版本的区别。 - gdogg371
1
没问题,需要补充的是在Python3的某些最近版本中,字典按照它们的“插入”顺序排序。请参见https://docs.python.org/3/whatsnew/3.7.html。 - R. Arctor

2
在Python中,字典没有特定的顺序,因此您不能对它们进行下标操作。
解决这个问题的方法之一是将`dict_values`对象转换为列表。
sub_dict = dict(list(pair_dict.items())[start_chunk:end_chunk])

如果您想进行下标操作,使用 orderedDict 而非 dict 更为合适。


嗨。我在我的真实代码中使用OrderedDict,只是为了让代码更易于理解,我将其省略了。 - gdogg371

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接