-
波斯汪
array_of_dicts = [{"a": 1, "b": 2}, {"a": 1, "b": "zz", "c": "cc"}, {"a": 1, "b": "2"}]def get_same_vals(dicts): keys = [] for key in dicts[0].keys(): is_same = True for each_dict in array_of_dicts: if not key in each_dict or each_dict[key] != dicts[0][key]: is_same = False if is_same: keys.append(key) return keysprint(get_same_vals(array_of_dicts))
-
繁华开满天机
正如其他答案中所建议的,创建一个对每个键进行分组的主字典,然后检查它们的唯一性。# all keys are the same, so get the listkeys = array_of_dicts[0].keys()# collapse values into a single dictionaryvalue_dict = {k: set(d[k] for d in array_of_dicts) for k in keys}# get list of all single-valued keysprint([k for k, v in value_dict.items() if len(v) == 1])
-
回首忆惘然
这是一个可能的解决方案,它也适用于字典结构不同(具有不同/额外键)的情况:array_of_dicts = [{"a": 1, "b": 2}, {"a": 1, "b": "zz"}, {"a": 1, "b": "2"}]def is_entry_in_all_dicts(key, value): identical_entries_found = 0 for dict in array_of_dicts: if key in dict: if dict[key] == value: identical_entries_found += 1 if identical_entries_found == len(array_of_dicts): return True return False result = []for dict in array_of_dicts: for key, value in dict.items(): if is_entry_in_all_dicts(key, value): if key not in result: result.append(key)print(result)输出['a']
-
30秒到达战场
如果您确定它们都具有相同的键,则可以像这样迭代它们的键和列表:array_of_dicts = [{"a": 1, "b": 2}, {"a": 1, "b": "zz"}, {"a": 1, "b": "2"}]def get_same_vals(dicts): keys = [] for key in dicts[0].keys(): is_same = True for each_dict in dicts: if each_dict[key] != dicts[0][key]: is_same = False if is_same: keys.append(key) return keysprint(get_same_vals(array_of_dicts))# Prints ['a']对于低效的代码,我深表歉意;我没有花那么长时间来编写这个代码。
-
当年话下
如果每个字典都有相同的键,您可以将这些值组合成集合并查找包含一个元素的集合:[list(x.keys())[0] for x in [{k:set([e[k] for e in list_of_dicts])} for k in list_of_dicts[0]] if len(list(x.values())[0]) == 1]输出:['a']
-
四季花海
这是一个更简洁的方法from functools import reducearray_of_dicts = [{"a": 1, "b": 2}, {"a": 1, "c": "zz"}, {"a": 1, "d": "2"}]result = reduce(lambda a, b: a.intersection(b),list(map(lambda x: set(x.keys()), array_of_dicts)))