过滤词典列表包含相同的键,值

时间:2018-04-03 11:01:56

标签: python

我有一个词典列表,如:

l = [
  {'a': 123, 'b': 456},
  {'a': 322, 'b': 44454},
  {'a': 123, 'b': 134}
]

我想根据每个字典的键a来过滤列表。如果键,值'a': 123存在于列表的任何其他字典中,则删除这两个中的任何一个,我想要过滤结果,如:

[
  {'a': 123, 'b': 456}, 
  {'a': 3222, 'b': 44454}
]
# 1st and 3rd dict have same 'a': 123 so remove 3rd dictionary, don't care about value of 'b'.

# or

[
  {'a': 3222, 'b': 44454}, 
  {'a': 123, 'b': 134}
]
# 1st and 3rd dict have same 'a': 123 so remove 1st dictionary. Don't care about value of 'b'.

我尝试了不同的方法,但如果词典列表的所有键和值都相同,则所有方法都会成功。

import itertools, operator, pprint
from operator import itemgetter

l = [
  {'a': 123, 'b': 456},
  {'a': 322, 'b': 44454},
  {'a': 123, 'b': 134}
]

getvals = operator.itemgetter('a', 'b')
l.sort(key=getvals)
result = []

for k, g in itertools.groupby(l, getvals):
    result.append(g.next())

l[:] = result
pprint.pprint(l)

但结果是

[{'a': 123, 'b': 134}, {'a': 123, 'b': 456}, {'a': 322, 'b': 44454}]

如何过滤我的列表?

3 个答案:

答案 0 :(得分:2)

试试这个:

values = []
new_x = []
for d in l:
    if not d['a'] in values:
        new_x.append(d)
        values.append(d['a'])

print(new_x)

答案 1 :(得分:2)

您可以创建一个简单的看到的列表,以便在迭代它们时存储您的值,然后仅将您以前没有见过的值的词典导出到新列表,例如

def filter_dicts(target, key):
    seen = set()  # a temporary set to store already visited values
    return [d for d in target if d[key] not in seen and not seen.add(d[key])]

您可以使用以下方法进行测试:

l = [
    {'a': 123, 'b': 456},
    {'a': 322, 'b': 44454},
    {'a': 123, 'b': 134}
]
k = filter_dicts(l, "a")
#   [
#     {'a': 123, 'b': 456},
#     {'a': 322, 'b': 44454}
#   ]

订单不必匹配,因为dict通常是无序结构。

答案 2 :(得分:2)

另一种方法是:

SELECT 100 * ( select sum(s.bytes) 
from dba_segments s 
where TABLESPACE_NAME='USERS')  / sum(MAXBYTES) used
FROM dba_data_files
WHERE tablespace_name = 'USERS'
group by 100 * ( select sum(s.bytes) 
from dba_segments s 
where TABLESPACE_NAME='USERS') 

输出:

l = [{'a': 123, 'b': 456}, {'a': 322, 'b': 44454}, {'a': 123, 'b': 134}]

newList = []

#Get all unique values of key 'a'.
values = list(set(i['a'] for i in l))

# Filter the dictionary.
for i in l:
    for v in values:
        if i['a']==v:
            newList.append(i)
            values.remove(v)
            break

#Print result.
print(newList)