Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching key-value by position from dictionary

Tags:

python

I use a python dictionary tel = {'jack': 4098, 'sape': 4139.....,'john':5147} Is there any way to fetch all the values located between index range? for example, all values located from the 5th-10th position...

Thanks, Nathan

like image 867
Nathan Avatar asked May 19 '26 17:05

Nathan


2 Answers

There are no indexes/positions in a python dictionary. Key/value pairs do not have any specific order.

If you want to select specific positions from the dictionary, you have to give it some criteria/order.

For example, according to alphabetical order of names:

sorted(tel.items())[5:11]

returns a list of 5 tuples of (name, number) from the positions 5-10 in the alphabetical order.

like image 92
eumiro Avatar answered May 21 '26 06:05

eumiro


You should not be referencing Python dictionaries by index. Python dictionaries order of storage of items is arbitrary and denoting it by index is bound to fail. Instead you use reference it by keys whenever it comes to dictionaries. When it comes to Ordered Dict, the standard libraries collections.OrderedDict does not seem to provide index method, but, there are certain OrderedDict odict, where you can reference elements using index.

like image 45
Senthil Kumaran Avatar answered May 21 '26 07:05

Senthil Kumaran