Python – 字典中键的唯一值
有时,在使用Python字典时,我们可能会遇到需要提取字典列表中特定键的唯一值的问题。这类问题在日常编程和 Web 开发领域中非常常见。让我们讨论可以执行此任务的某些方式。
Input : test_list = [{‘geeks’: 10, ‘for’: 8, ‘best’: 10}, {‘best’: 10}]
Output : [10]
Input : test_list = [{‘best’: 11}]
Output : [11]
方法 #1:使用循环 + set()
上述功能的组合可以用来解决这个问题。在此,我们在循环中提取 key 的所有元素,然后将提取的列表转换为 set 以获得唯一值。
# Python3 code to demonstrate working of
# Unique Values of Key in Dictionary
# Using loop + set()
# initializing list
test_list = [{'Gfg' : 5, 'is' : 6, 'best' : 7, 'for' : 8, 'geeks' : 10},
{'Gfg' : 9, 'is' : 4, 'best' : 7, 'for' : 4, 'geeks' :7},
{'Gfg' : 2, 'is' : 10, 'best' : 8, 'for' : 9, 'geeks' : 3}]
# printing original list
print("The original list is : " + str(test_list))
# initializing key
op_key = 'best'
# Unique Values of Key in Dictionary
# Using loop + set()
res = []
for sub in test_list:
res.append(sub[op_key])
res = list(set(res))
# printing result
print("The unique values of key : " + str(res))
The original list is : [{‘for’: 8, ‘best’: 7, ‘is’: 6, ‘Gfg’: 5, ‘geeks’: 10}, {‘for’: 4, ‘best’: 7, ‘is’: 4, ‘Gfg’: 9, ‘geeks’: 7}, {‘for’: 9, ‘best’: 8, ‘is’: 10, ‘Gfg’: 2, ‘geeks’: 3}]
The unique values of key : [8, 7]
方法#2:使用列表推导
这是解决此问题的另一种方法。在此,我们以与上述方法类似的方式执行,但采用速记方法。
# Python3 code to demonstrate working of
# Unique Values of Key in Dictionary
# Using list comprehension
# initializing list
test_list = [{'Gfg' : 5, 'is' : 6, 'best' : 7, 'for' : 8, 'geeks' : 10},
{'Gfg' : 9, 'is' : 4, 'best' : 7, 'for' : 4, 'geeks' :7},
{'Gfg' : 2, 'is' : 10, 'best' : 8, 'for' : 9, 'geeks' : 3}]
# printing original list
print("The original list is : " + str(test_list))
# initializing key
op_key = 'best'
# Unique Values of Key in Dictionary
# Using list comprehension
res = list(set(sub[op_key] for sub in test_list))
# printing result
print("The unique values of key : " + str(res))
The original list is : [{‘for’: 8, ‘best’: 7, ‘is’: 6, ‘Gfg’: 5, ‘geeks’: 10}, {‘for’: 4, ‘best’: 7, ‘is’: 4, ‘Gfg’: 9, ‘geeks’: 7}, {‘for’: 9, ‘best’: 8, ‘is’: 10, ‘Gfg’: 2, ‘geeks’: 3}]
The unique values of key : [8, 7]