How to Index into Dictionary in Python?

Python Tutorials

Unlike the list, the items in the dictionary are not indexed, instead, it stores items in ‘key: value’ pairs. However, in versions of Python 3.7 or greater, the order of the items in the dictionary is preserved.

Taking advantage of this feature (ordered items), you can easily index ‘key: value’ pairs of the dictionary in the following ways.

Index Keys from Dictionary

Call the list(iterable) method with a dictionary as iterable to get a list of keys. Now you can use the list[index] to access the keys via its index.

>>> d = {'id': '256', 'name': 'Justin'}
>>> k_index = list(d)
>>> k_index[0]
'id'
>>> k_index[1]
'name'

Index Values from Dictionary

Use the list(dict.values()) syntax to get a list of values instead of keys. Now use the list[index] to get the values at index in list.

>>> d = {'id': '256', 'name': 'Justin'}
>>> v_index = list(d.values())
>>> v_index[0]
256
>>> v_index[1]
'Justin'

Index Key:Value Pair from Dictionary

Call the dict.items() with dict as a dictionary to get a view object containing key-value pairs in tuples. Call the list(args) with args as the view object to convert it into a list.

>>> d = {'id': '256', 'name': 'Justin'}
>>> obj = d.items()
>>> kv_index = list(obj)
>>> kv_index[0]
('id', '256')
>>> kv_index[1]
('name', 'Justin')

Leave a Reply

Your email address will not be published. Required fields are marked *