为了账号安全,请及时绑定邮箱和手机立即绑定

在Python中,如何在字典数组中查找值相同的键?

在Python中,如何在字典数组中查找值相同的键?

智慧大石 2023-09-12 15:51:57
我正在使用Python 3.8。我有一系列字典,所有字典都有相同的键......list_of_dicts = [{"a": 1, "b": 2}, {"a": 1, "b": "zz"}, {"a": 1, "b": "2"}]如何返回所有值都相同的键列表?例如,上面的内容只是["a"]因为所有三个字典都有“a”= 1。
查看完整描述

6 回答

?
波斯汪

TA贡献1811条经验 获得超4个赞


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 keys


print(get_same_vals(array_of_dicts))  


查看完整回答
反对 回复 2023-09-12
?
繁华开满天机

TA贡献1816条经验 获得超4个赞

正如其他答案中所建议的,创建一个对每个键进行分组的主字典,然后检查它们的唯一性。


# all keys are the same, so get the list

keys = array_of_dicts[0].keys()


# collapse values into a single dictionary

value_dict = {k: set(d[k] for d in array_of_dicts) for k in keys}


# get list of all single-valued keys

print([k for k, v in value_dict.items() if len(v) == 1])


查看完整回答
反对 回复 2023-09-12
?
回首忆惘然

TA贡献1847条经验 获得超11个赞

这是一个可能的解决方案,它也适用于字典结构不同(具有不同/额外键)的情况:


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']


查看完整回答
反对 回复 2023-09-12
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

如果您确定它们都具有相同的键,则可以像这样迭代它们的键和列表:


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 keys


print(get_same_vals(array_of_dicts))

# Prints ['a']

对于低效的代码,我深表歉意;我没有花那么长时间来编写这个代码。


查看完整回答
反对 回复 2023-09-12
?
当年话下

TA贡献1890条经验 获得超9个赞

如果每个字典都有相同的键,您可以将这些值组合成集合并查找包含一个元素的集合:

[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']


查看完整回答
反对 回复 2023-09-12
?
四季花海

TA贡献1811条经验 获得超5个赞

这是一个更简洁的方法


from functools import reduce

array_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)))


查看完整回答
反对 回复 2023-09-12
  • 6 回答
  • 0 关注
  • 98 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信