gdogg371
gdogg371

Reputation: 4152

Subset a dictionary in Python 3

How can I subset a dictionary using Python 3? Using Python 2, the below works:

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)

However, in this version of Python I now get the following error:

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

Upvotes: 3

Views: 314

Answers (2)

R. Arctor
R. Arctor

Reputation: 728

The issue you are having is just as the error says. The special 'dict_values' object is not subscriptable. If you convert the pair_dict.items() / pair_dict.values() to a list before trying to subscript them you will get the desired result.

The reason this works in Python2 is that those methods used to return a list object rather than an iterator.

Upvotes: 3

xfnw
xfnw

Reputation: 84

In python, Dictionaries are not in a specific order, so therefor you cannot subscript them.

One solution to this would be to convert the dict_values object to a list.

sub_dict = dict(list(pair_dict.items())[start_chunk:end_chunk])

However it is probably better to use a orderedDict instead of a dict if you would like to subscript it.

Upvotes: 2

Related Questions