Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按特定值筛选dict_Python_Dictionary_Filtering - Fatal编程技术网

Python 按特定值筛选dict

Python 按特定值筛选dict,python,dictionary,filtering,Python,Dictionary,Filtering,我有一张像这样的纸 db = { 'ObjectID': ['-1', '6', '10', '13', '13', '13', '-1', '-1', '-1', '-1', '-1', '-1'], 'Test_value': ['25', '0,28999999', '100,00000000', 'Geometry', '126641,847400000000', '473106,185600000030', ' ', ' ', ' ', ' ', ' ', ' '], 'Has_e

我有一张像这样的纸

db = {
'ObjectID': ['-1', '6', '10', '13', '13', '13', '-1', '-1', '-1', '-1', '-1', '-1'], 
'Test_value': ['25', '0,28999999', '100,00000000', 'Geometry', '126641,847400000000', '473106,185600000030', ' ', ' ', ' ', ' ', ' ', ' '], 
'Has_error': ['true', 'true', 'true', 'true', 'true', 'true', 'false', 'false', 'false', 'false', 'false', 'false'], 
'Message': ['Table row counts are different', 'ObjectID 6 is different for Field DIKTE_BRUGDEK', 'ObjectID 10 is different for Field RICHTING_1',                'ObjectID 13 is different for Field GEOMETRIE', 'ObjectID 13 is different for Field X', 'ObjectID 13 is different for Field Y', 'Shape types are the          same', 'Feature types are the same', 'Feature class extents are the same', 'GeometryDefs are the same', 'Field properties are the same', 'Spatial             references are the same'], 'Identifier': ['Table', 'FeatureClass', 'FeatureClass', 'FeatureClass', 'FeatureClass', 'FeatureClass', 'FeatureClass',            'FeatureClass', 'FeatureClass', 'GeometryDef', 'Field', 'SpatialReference'], 
'Base_value': ['23', '0,19000000', '394,00000000', 'Geometry', '126530,700000000000', '473095,700000000010', ' ', ' ', ' ', ' ', ' ', ' ']}
我想根据“ObjectID”列表中的条目将其分解为更小的子集,即-1。 我的第一次尝试是建立一个值索引,如:

filter_ind = []
for k,v in db.iteritems():
    for i in xrange(len(v)):
            if (k == 'ObjectID') and (int(v[i]) != -1):
                filter_ind.append(i) 
然后我尝试构建一个新的dict,使用filter\u ind作为排序过滤器: 过滤器中i的dict((k,v[i])表示k,v表示db.iteritems())

我得到的只是最后一个匹配项,因为
v
不再是列表:
{'ObjectID':'13','Test_value':'47310618560000030','Has_error':'true',
'Message':'ObjectID 13与字段Y不同',
‘标识符’:‘FeatureClass’,‘基本值’:‘4730950000000010’}


问:有没有其他方法可以根据dict本身的特定值过滤dict?如果这被认为是一种相对严格的正向方法,那么使用索引作为过滤器来创建新dict的智能方法是什么?已经谢谢了。

我想你把这件事复杂化了一点。首先,不需要嵌套循环。您可以通过以下方式获得所需的索引:

oids = db['ObjectID']
for i, id in enumerate(oids):
    if id != -1
        filter_ind.append(i) 
或者更简洁地说

filter_ind = [i for i, id in enumerate(oids) if id != '-1']
然后,您可以使用ID筛选各个列表:

dict((key, [val[i] for i in filter_ind]) for key, val in db.iteritems())

下面是我做的:

new_db=db.copy()
fltr=[x=='-1' for x in new_db['ObjectID']] #Not actually necessary, but makes the code a little more readable

for k,v in new_db.items():
    new_db[k]=[x for i,x in enumerate(new_db[k]) if fltr[i]]  #replace old lists with new filtered ones.

这与senderle(我想)给出的答案非常相似。我使用布尔列表,而另一个答案使用索引。我的可能效率不高,但我更容易阅读/理解。

这里是另一个选项:

from operator import itemgetter

iget = itemgetter(*(i for i, id in enumerate(db['ObjectID']) if int(id) != -1))
result = dict((k, list(iget(v))) for k, v in db.items())
如果您使用的是2.7:

from itertools import compress
indexes = [(x != -1) for x in db['ObjectID']]
result = dict((k, compress(v, indexes)) for k, v in db.iteritems())
我喜欢这个:

[dict(zip(db.keys(),e)) for e in zip(*db.values()) if e[0]!='-1']

它返回一个DICT列表,不包括带-1的DICT。

这实际上是一个罕见的情况,您可以使用:


正如我所说,值列表应该只包含基于
db['ObjectID']索引的条目-1
(这是
[1,2,3,4,5]
。谢谢,我最初的解释是你想要一个目录列表,类似于
[{'ObjectID':'6',…},{'ObjectID':'10',…},…]
。有相同的印象…:-/这很简单。谢谢!@larsvegas,我要简单地补充一下,这是一本有点非传统的字典。你有没有考虑过把
id
作为主键,把文件名作为内部字典的键来构建它作为字典的字典?还没有考虑过,没有。。。我只是从dbf中读取这样的数据,所以我想保持列、行结构完整。我想这是高级选项,至少对我来说可读性较差。
*
-运算符在这里做什么?它是运算符吗?
*
这里有时被称为splat运算符,它在文档中被调用。基本上
foo(*[1,2,3])
相当于
foo(1,2,3)
。该函数接受任意数量的索引(或键),并返回一个函数,该函数可用于过滤序列(或映射)以仅获取指定元素。
from itertools import compress

sels = [x != '-1' for x in db['ObjectID']]
comp = {key: list(compress(vals, sels)) for key, vals in db.items()}