Python - Perform operation on each key dictionary


Python is a capable programming language known for its effortlessness and versatility. One of its key highlights is the capacity to work with dictionaries, which are data structures that store key-value sets. In numerous scenarios, we got to perform operations on each key in a dictionary. Python's straightforwardness and adaptability make it a perfect choice for working with dictionaries and performing operations on their keys. In this article, we are going investigate three approaches to attain this objective in Python, besides step-by-step algorithms and syntax cases. Let's plunge in! 

Python Dictionary Operations

Performing operations on each key in a dictionary can be accomplished by utilizing diverse approaches in Python. One common approach is employing a for loop, where each key is iterated over and the required operation is performed. Another approach is utilizing dictionary comprehension, which permits the brief creation of a modern dictionary with adjusted keys. The map() function can be utilized, applying a specified function to each key and returning an altered outline question. Understanding these hypothetical concepts gives the establishment for executing code to perform operations on dictionary keys in Python. 

Approach 1:  Using a for loop

The primary approach includes employing a for loop to repeat over each key within the dictionary. Here's the algorithm −

Algorithm

  • Initialize an empty dictionary.

  • Repeat each key within the unique dictionary.

  • Perform the specified operation on each key.

  • Update the dictionary with the altered key.

Example

# Original dictionary
original_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# New dictionary
new_dict = {}

# Iterate over each key
for key in original_dict:
    # Perform operation on the key (in this case, converting it to uppercase)
    modified_key = key.upper()
    
    # Update the new dictionary with the modified key
    new_dict[modified_key] = original_dict[key]

# Print the new dictionary
print(new_dict)

Output

{'KEY1': 'value1', 'KEY2': 'value2', 'KEY3': 'value3'}

Within the over code, we make a modern dictionary new_dict to store the altered keys. The for loop iterates over each key within the unique dictionary, and inside the loop, we change over each key to capitalize utilizing the upper() method. At last, we upgrade the unused word reference with the adjusted key value combined. 

Approach 2:  Using dictionary comprehension

The second approach utilizes dictionary comprehension, a brief and rich way to form dictionaries in Python. Here's the algorithm −

Algorithm

  • Make a modern dictionary utilizing dictionary comprehension.

  • Iterate each key within the unique dictionary

  • Perform the required operation on each key.

  • Overhaul the modern dictionary with the adjusted key-value combined.

Example

# Original dictionary
original_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Create a new dictionary using dictionary comprehension
new_dict = {key.upper(): value for key, value in original_dict.items()}

# Print the new dictionary
print(new_dict)

Output

{'KEY1': 'value1', 'KEY2': 'value2', 'KEY3': 'value3'}

Within the code over, we use dictionary comprehension to form the modern dictionary new_dict. The comprehension repeats over each key-value match within the unique word reference utilizing the items() method. We change over each key to capitalize inside the comprehension and dole out the modified key-value combine with the new dictionary.

Approach 3: Using the map() function

The third approach includes utilizing the map() function, which may be a built-in Python function that applies an indicated function to each thing in an iterable. Here's the algorithm −

Algorithm

  • Characterize a function that performs the required operation on a key.

  • Use the map() function to apply the function to each key within the unique dictionary.

  • Change over the coming about outline question to a dictionary.

Example

# Original dictionary
original_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Define a function to modify the key
def modify_key(key):
    return key.upper()

# Use map() to apply the function to each key
modified_keys = map(modify_key, original_dict.keys())

# Convert the map object to a dictionary
new_dict = dict(zip(modified_keys, original_dict.values()))

# Print the new dictionary
print(new_dict)

Output

{'KEY1': 'value1', 'KEY2': 'value2', 'KEY3': 'value3'}

Within the code over, we characterize a function modify_key() that takes a key as input and returns the adjusted key (in this case, changed over to uppercase). We utilize the map() function to apply this function to each key within the unique dictionary. The coming about outline question is at that point changed over to a dictionary utilizing the dict() function and the zip() function to combine the adjusted keys with the initial values. 

Conclusion

Performing operations on each key in a dictionary is a common errand in Python programming. In this article, we investigated three approaches to attain this objective. We talked about employing a for loop, dictionary comprehension, and the map() function. Each approach has its preferences and can be used depending on the particular necessities of the assignment. By leveraging these strategies, you'll be able easily to control keys in dictionaries to suit your needs. Keep in mind to choose the approach that best fits your situation and consider variables such as execution, meaningfulness, and viability.

Updated on: 01-Sep-2023

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements