w3resource

Python: Find the dictionary key whose case is different than all other keys


Dictionary Key with Odd Case

Write a Python program to find the dictionary key whose case is different from all other keys.

Input:
{'red': '', 'GREEN': '', 'blue': 'orange'}
Output:
GREEN

Input:
{'RED': '', 'GREEN': '', 'orange': '#125GD'}
Output:
orange

Visual Presentation:

Python: Find the dictionary key whose case is different than all other keys.

Sample Solution:

Python Code:

# License: https://bit.ly/3oLErEI

def test(dict_data):
    # Iterate over each key in the dictionary
    for different in dict_data:
        # Check if the case of the current key is different from all other keys
        if all(k.islower() != different.islower() for k in dict_data if k != different):
            # Return the key with a different case
            return different
 
# Example 1
dict_data1 = {"red": "", "GREEN": "", "blue": "orange"}
print("Original dictionary key-values:")
print(dict_data1)
print("Find the dictionary key whose case is different than all other keys:")
print(test(dict_data1))

# Example 2
dict_data2 = {"RED": "", "GREEN": "", "orange": "#125GD"}
print("\nOriginal dictionary key-values:")
print(dict_data2)
print("Find the dictionary key whose case is different than all other keys:")
print(test(dict_data2))

Sample Output:

Original dictionary key-values:
{'red': '', 'GREEN': '', 'blue': 'orange'}
Find the dictionary key whose case is different than all other keys:
GREEN

Original dictionary key-values:
{'RED': '', 'GREEN': '', 'orange': '#125GD'}
Find the dictionary key whose case is different than all other keys:
orange

Flowchart:

Flowchart: Python - Find the dictionary key whose case is different than all other keys.

For more Practice: Solve these Related Problems:

  • Write a Python program to identify the one dictionary key that has a different case format compared to the others.
  • Write a Python program to compare keys in a dictionary and return the key whose case (upper/lower) is the outlier.
  • Write a Python program to use collections.Counter on the case forms of dictionary keys and detect the one that deviates.
  • Write a Python program to iterate through a dictionary and output the key whose letter case is not consistent with the majority.

Go to:


Previous: Find the number which when appended to the list makes the total 0.
Next: Find the sum of the even elements that are at odd indices in a given list.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.