python取出字典的某个键_在Python中,如何获取字典中特定键的下一个和上一个键:值?...

本文介绍如何使用Python的OrderedDict实现快速查找某个键值对的前一个和后一个键值对,这对于需要按插入顺序遍历或调整字典的场景非常实用。作者通过实例展示了如何通过内置方法找到指定键的链接,进而获取前后邻居。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

Okay, so this is a little hard to explain, but here goes:

I have a dictionary, which I'm adding content to. The content is a hashed username (key) with an IP address (value).

I was putting the hashes into an order by running them against base 16, and then using Collection.orderedDict.

So, the dictionary looked a little like this:

d = {'1234': '8.8.8.8', '2345':'0.0.0.0', '3213':'4.4.4.4', '4523':'1.1.1.1', '7654':'1.3.3.7', '9999':'127.0.0.1'}

What I needed was a mechanism that would allow me to pick one of those keys, and get the key/value item one higher and one lower. So, for example, If I were to pick 2345, the code would return the key:value combinations '1234:8.8.8.8' and '3213:4.4.4.4'

So, something like:

for i in d:

while i < len(d)

if i == '2345':

print i.nextItem

print i.previousItem

break()

解决方案

As seen in the OrderedDict source code,

if you have a key and you want to find the next and prev in O(1) here's how you do that.

>>> from collections import OrderedDict

>>> d = OrderedDict([('aaaa', 'a',), ('bbbb', 'b'), ('cccc', 'c'), ('dddd', 'd'), ('eeee', 'e'), ('ffff', 'f')])

>>> i = 'eeee'

>>> link_prev, link_next, key = d._OrderedDict__map['eeee']

>>> print 'nextKey: ', link_next[2], 'prevKey: ', link_prev[2]

nextKey: ffff prevKey: dddd

This will give you next and prev by insertion order. If you add items in random order then just keep track of your items in sorted order.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值