[英]How to find unique set values in the list of dictionaries in Python
我有一個具有相同鍵集的字典列表。 我需要在所有詞典中找到具有唯一值的單個鍵或具有唯一值組合的一組鍵。
例子:
# Case 1.
tags1 = [{'a': 10, 'b': 2, 'c': 3},
{'a': 11, 'b': 2, 'c': 4},
{'a': 12, 'b': 2, 'c': 3}]
# Case 2.
tags2 = [{'a': 10, 'b': 2, 'c': 3},
{'a': 10, 'b': 2, 'c': 4},
{'a': 12, 'b': 2, 'c': 3}]
# If there is a key with unique values for each key in the list of dicts
# than it's simple e.g. a: 10, a: 11, a: 12 in Case 1
# But in Case 2 where there is no a single key with such properties,
# than there is a problem
def unique_tag(tags):
metric_tags = list(tags[0].keys())
for tag in metric_tags:
values = set([i[tag] for i in tags if tag in i])
if len(values) == len(tags):
return [tag]
# ==== What we have: ====
# Case 1. - works
unique_set_of_tags = unique_tags(tags1)
print(unique_set_of_tags)
>>> ['a']
# Case 2. - doesn't work
unique_set_of_tags = unique_tags(tags2)
print(unique_set_of_tags)
>>> []
# ==== What we want: =====
# Case 2.
unique_set_of_tags = unique_tags(tags2)
print(unique_set_of_tags)
>>> ['a', 'c']
# because combination of values for this tags are unique
# [(10, 3), (10, 4), (12, 3)]
我猜你的代碼中的問題是你沒有組合多個元素來檢查嵌套組合(你只檢查列表是否只有唯一值但你還需要檢查列表列表是否唯一)。
我寧願制作一個矩陣,然后檢查給定軸的所有可能組合(如果您有重復的鍵並且您不會使用它們訪問任何值,則使用字典列表看起來很奇怪)。 因此,例如,我們可以生成一個包含 numpy 的矩陣:
import numpy as np
np.array([[v for v in d.values()] for d in tags1])
[[10 2 3]
[11 2 4]
[12 2 3]]
現在我們需要檢查給定一列或多列,所有水平切片(行)的序列是否唯一。 我們可以使用 itertools 模塊來生成我們想要檢查的列的組合:
import numpy as np
import itertools
def unique_set_of_tags(tags):
matrix = np.array([[v for v in d.values()] for d in tags])
m = matrix.shape[0]
n = matrix.shape[1]
for n_elem in range(n):
for c in itertools.combinations([i for i in range(m)], r=n_elem+1):
if np.unique(matrix[:, c], axis=0).shape[0] == m:
return [k for i, k in enumerate(list(tags[0].keys())) if i in c]
return []
在我們擁有對應於唯一組合的列之后,我們從垂直軸索引轉換回字典的鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.