在Python中,如何获取字典中特定键的下一个和上一个键:值? [英] In Python, How can I get the next and previous key:value of a particular key in a dictionary?

查看:1294
本文介绍了在Python中,如何获取字典中特定键的下一个和上一个键:值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以这有点难以解释,但是在这里:

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

我有一本字典,正在向其中添加内容.内容是带有IP地址(值)的哈希用户名(键). 我通过将哈希针对基数为16的顺序进行排序,然后使用Collection.orderedDict. 因此,字典看起来像这样:

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'}

我需要的是一种机制,使我可以选择其中一个键,并使键/值项一个高一个,另一个低一个.因此,例如,如果我选择2345,代码将返回key:value组合'1234:8.8.8.8'和'3213:4.4.4.4'

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'

所以,像这样:

for i in d:
  while i < len(d)
   if i == '2345':
     print i.nextItem
     print i.previousItem
     break()

推荐答案

OrderedDict源代码, 如果您有密钥,并且想在O(1)中找到下一个和上一个,请按以下步骤操作.

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.

这篇关于在Python中,如何获取字典中特定键的下一个和上一个键:值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆