python 字典取最后一个元素,如何访问字典中的第一个和最后一个元素?

Before posting, I have already gone through Access an arbitrary element in a dictionary in Python, butI'm uncertain about this.

I have a long dictionary and I've to get the values of its first and last keys. I can use dict[dict.keys()[0]] and dict[dict.keys()[-1]] to get the first and last elements, but since the key:value pairs are outputted in a random form(as in the positioning of the key:value pairs is random), will the solution provided in this link always work?

解决方案

Use an OrderedDict, because a normal dictionary doesn't preserve the insertion order of its elements when traversing it. Here's how:

# import the right class

from collections import OrderedDict

# create and fill the dictionary

d = OrderedDict()

d['first'] = 1

d['second'] = 2

d['third'] = 3

# retrieve key/value pairs

els = list(d.items()) # explicitly convert to a list, in case it's Python 3.x

# get first inserted element

els[0]

=> ('first', 1)

# get last inserted element

els[-1]

=> ('third', 3)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值