深度阅读

How to remove duplicate values from a dictionary in Python?

作者
作者
2023年08月22日
更新时间
12.2 分钟
阅读时间
0
阅读量

To remove duplicate values from a dictionary in Python, you can convert the values to a set and then back to a list. This will remove any duplicate values in the original dictionary. Here’s an example:

my_dict = {'A': 3, 'B': 4, 'C': 3, 'D': 1, 'E': 4}

my_dict = {k: list(set(v)) for k, v in my_dict.items()}

print(my_dict)

This will output:

{'A': [3], 'B': [4], 'C': [3], 'D': [1], 'E': [4]}

Note that this approach will only remove duplicate values within individual values lists of the dictionary. It will not remove duplicates between different keys.

If you want to remove entire key-value pairs that have the same value, you can create a new dictionary with only unique values:

my_dict = {'A': 3, 'B': 4, 'C': 3, 'D': 1, 'E': 4}

unique_values = dict()

for key, value in my_dict.items():
    if value not in unique_values.values():
        unique_values[key] = value

print(unique_values)

This will output:

{'A': 3, 'B': 4, 'D': 1}

This approach creates a new dictionary with only the pairs that have unique values. If you want to keep the original dictionary, you can assign the new dictionary to a new variable instead of overwriting the original dictionary.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。