📜  从字典列表中获取所有唯一键的Python程序

📅  最后修改于: 2022-05-13 01:56:56.443000             🧑  作者: Mango

从字典列表中获取所有唯一键的Python程序

给定一个由N个字典组成的列表arr[] ,任务是从给定的字典列表中找到唯一键的总和。

例子:

使用链式可迭代工具的方法:可以使用set()和 keys() 方法和链式可迭代工具来解决上述问题。



请按照以下步骤解决问题:

  • 使用链式迭代工具遍历每个字典的所有键
  • 将一组键存储在一个列表中,比如res
  • 打印列表res作为所需答案。

下面是上述方法的实现:

Python3
# Python3 program for the above approach
from itertools import chain
  
  
# Function to print all unique keys
# present in a list of dictionaries
def UniqueKeys(arr):
  
    # Stores the list of unique keys
    res = list(set(chain.from_iterable(sub.keys() for sub in arr)))
  
    # Print the list
    print(str(res))
  
# Driver Code
arr = [{'my': 1, 'name': 2}, 
       {'is': 1, 'my': 3},
       {'ria': 2}]
UniqueKeys(arr)


Python3
# Python3 program for the above approach
  
from itertools import chain
  
# Function to print all unique keys
# from a list of dictionaries
def UniqueKeys(arr):
  
    # Stores the list of unique keys
    res = list(set(val for dic in arr for val in dic.keys()))
  
    # Print the list
    print(str(res))
  
# Driver Code
  
# Input
arr = [{'my': 1, 'name': 2}, 
       {'is': 1, 'my': 3},
       {'ria': 2}]
  
UniqueKeys(arr)


输出:
['is', 'ria', 'my', 'name']

时间复杂度: O(N * maxm),其中maxm表示最长字典的大小。
辅助空间: O(N * maxm)

使用List Comprehension 和Dictionary Comprehension 的方法:可以交替使用set() 和keys() 方法解决问题,使用List Comprehension 和Dictionary Comprehension 来解决问题。

请按照以下步骤解决问题:

  • 使用 List Comprehension 和 Dictionary Comprehension 遍历每个字典的所有键,然后将键集存储在一个列表中,比如res
  • 打印列表res作为所需答案。

下面是上述方法的实现:

蟒蛇3

# Python3 program for the above approach
  
from itertools import chain
  
# Function to print all unique keys
# from a list of dictionaries
def UniqueKeys(arr):
  
    # Stores the list of unique keys
    res = list(set(val for dic in arr for val in dic.keys()))
  
    # Print the list
    print(str(res))
  
# Driver Code
  
# Input
arr = [{'my': 1, 'name': 2}, 
       {'is': 1, 'my': 3},
       {'ria': 2}]
  
UniqueKeys(arr)
输出:
['ria', 'my', 'name', 'is']

时间复杂度: O(N * maxm),其中maxm表示最长字典的大小。
辅助空间: O(N * maxm)