开发者

Fetching key-value by position from dictionary

I use a python dictionary tel = {'jack': 4098, 'sape': 4139.....,'john':5147} Is there any way to fetch all the values locate开发者_如何学编程d between index range? for example, all values located from the 5th-10th position...

Thanks, Nathan


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.


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.


Better late than never.

>>> tel = {'tel_1': 111, 'tel_2': 222, 'tel_3': 333, 'tel_4': 444} 
         
>>> for i in range(len(tel)):
>>>    key = list(tel.keys())[i]
>>>    print(key, ': ', tel[key])

tel_1 :  111
tel_2 :  222
tel_3 :  333
tel_4 :  444

Somewhat cumbersome, however

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜