📜  Python|测试字典是否包含唯一的键和值

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

Python|测试字典是否包含唯一的键和值

有时,我们只希望使用独特的元素并且不希望任何类型的重复,对于这些情况,我们需要有技术来解决这些问题。一个这样的问题可以是测试唯一的键和值。对于键,它们默认是唯一的,因此不需要外部测试,但对于值,我们需要有办法做到这一点。让我们测试一下可以做到这一点的各种方法。

方法#1:使用循环
在执行此特定任务的 Naive 方法中,我们可以检查每个值并将每个值插入字典中的列表/散列中,当我发生重复时,只需停止流程并返回 false。

# Python3 code to demonstrate
# check for unique values
# Using loops
  
# initializing dictionary
test_dict = {'Manjeet' : 1, 'Akash' : 2, 'Akshat' : 3, 'Nikhil' : 1}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# using loops
# check for unique values
flag = False
hash_val = dict()
for keys in test_dict:
    if test_dict[keys] in hash_val:
        flag = True
        break
    else :
        hash_val[test_dict[keys]] = 1
  
# print result
print("Does dictionary contain repetition : " + str(flag))
输出 :
The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True

方法 #2:使用len() + set() + values()
使用上述三个功能的组合可以很容易地解决这个问题。 set函数可用于将值转换为设置,删除重复项和 values函数可用于访问值。

# Python3 code to demonstrate
# check for unique values
# Using len() + set() + values()
  
# initializing dictionary
test_dict = {'Manjeet' : 1, 'Akash' : 2, 'Akshat' : 3, 'Nikhil' : 1}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# using len() + set() + values()
# check for unique values
flag = len(test_dict) != len(set(test_dict.values()))
  
# print result
print("Does dictionary contain repetition : " + str(flag))
输出 :
The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True