根据范围获取子字典 [英] Get the subdictionary based on range

查看:97
本文介绍了根据范围获取子字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字母,它具有坐标对作为键:ie:

I have a dictionary which has coordinate pairs as a keys: i.e.:

d = {(15,21): "value1", (7,45): "value2", (500,321): "value3",...}

现在我需要返回键位于一定范围内的元素的子字典:
例如:(6:16,20:46)的范围应该返回以下字典:
d = {(15,21):Value1,(7,45):value2} 如果该范围内没有其他元素。
有没有预定义的字典功能呢?你有什么建议吗?

Now I need to return a sub dictionary of the elements where the keys are within a certain range: for example: the range of (6:16, 20:46) should return the following dictionary: d = {(15,21): "Value1", (7,45): value2} if there was no other element in that range. Is there any predefined dictionary function to do that? ..or do you have any other suggestions?

Thx

推荐答案

这里有一种方法

d = {(15,21): "value1", (7,45): "value2", (500,321): "value3"}
x1, x2, y1, y2 = 6, 16, 20, 46 
dict((k,v) for k, v in d.iteritems() if x1<k[0]<x2 and y1<k[1]<y2)



Python 2.7已经添加了字典推导。最后一行变得更可读:

Python 2.7 has added dictionary comprehensions. The last line becomes more readable:

{k: v for k, v in d.iteritems() if x1<k[0]<x2 and y1<k[1]<y2}

这篇关于根据范围获取子字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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