Python Program to display keys with same values in a dictionary List

Python Program to display keys with same values in a dictionary List

Let's create a Python program that finds and displays keys in a list of dictionaries that have the same values.

Objective:

Given a list of dictionaries, display the keys that have the same values across these dictionaries.

Example:

For the list of dictionaries:

[{'a': 5, 'b': 6, 'c': 7}, {'d': 5, 'e': 6, 'f': 8}] 

The keys with same values are:

5: ['a', 'd'] 6: ['b', 'e'] 

Python Program:

def find_keys_with_same_values(dict_list): value_to_keys = {} # Traverse through each dictionary for d in dict_list: for key, value in d.items(): # If the value is already in our result dict, append the key if value in value_to_keys: value_to_keys[value].append(key) else: value_to_keys[value] = [key] # Filter out values that don't have multiple keys return {value: keys for value, keys in value_to_keys.items() if len(keys) > 1} # Test the function sample_dicts = [{'a': 5, 'b': 6, 'c': 7}, {'d': 5, 'e': 6, 'f': 8}] result = find_keys_with_same_values(sample_dicts) # Print the results print(f"List of Dictionaries: {sample_dicts}") print(f"Keys with Same Values: {result}") 

When you run the program, you'll get:

List of Dictionaries: [{'a': 5, 'b': 6, 'c': 7}, {'d': 5, 'e': 6, 'f': 8}] Keys with Same Values: {5: ['a', 'd'], 6: ['b', 'e']} 

Explanation:

  1. We initiate an empty dictionary value_to_keys to map values to the keys that have those values.
  2. We then traverse through each dictionary in the list.
  3. For each key-value pair, we check if the value is already a key in our value_to_keys dictionary. If it is, we append the current key to its list of keys. If not, we initialize it with a list containing the current key.
  4. After processing all dictionaries, we filter out the values in value_to_keys that don't have multiple keys associated with them. This is done using a dictionary comprehension.
  5. We then return the resulting dictionary.

This method efficiently identifies keys with the same values across a list of dictionaries.


More Tags

ping image-comparison zpl-ii chunking simulator robospice codeblocks expo monodevelop find-occurrences

More Programming Guides

Other Guides

More Programming Examples