Python program to extract target key from other key values

Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract particular key on basis of other matching record keys when there is exact match. Lets discuss certain ways in which this task can be performed.

Here's a Python program that can extract a target key from other key values:

 

# Define a dictionary with key-value pairs
data = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

# Define a function to extract a target key from the dictionary
def extract_target_key(data, target_key):
  # Check if the target key exists in the dictionary
  if target_key in data:
    return data[target_key]
  else:
    # If the target key does not exist, return None
    return None

# Call the function to extract the "age" key from the dictionary
result = extract_target_key(data, "age")

# Print the result
print(result) # Output: 30

In this program, we first define a dictionary data with key-value pairs. We then define a function extract_target_key that takes two arguments: data (the dictionary) and target_key (the key we want to extract).

Inside the function, we check if the target_key exists in the data dictionary using the in keyword. If it does exist, we return the corresponding value using the square bracket notation (data[target_key]). If the target_key does not exist, we return None.

Finally, we call the extract_target_key function with the data dictionary and the "age" key as arguments, and print the result.

Submit Your Programming Assignment Details