Certainly! Below is a Python script that extracts the key-value pairs from a dictionary where the value contains a space and appends them to an existing output array. Each qualifying key-value pair is stored as a tuple in the output array.
# Sample dictionary
input_dict = {
'key1': 'value1',
'key2': 'value with space',
'key3': 'another value with space',
'key4': 'nospacevalue',
}
# Existing output array with some initial values
output_array = [('existing_key1', 'existing_value1'), ('existing_key2', 'existing_value2')]
# Extract key-value pairs where the value contains a space and append to the existing output array
for key, value in input_dict.items():
if ' ' in value:
output_array.append((key, value))
# Print the updated output array
print(output_array)
Output:
[('existing_key1', 'existing_value1'), ('existing_key2', 'existing_value2'), ('key2', 'value with space'), ('key3', 'another value with space')]
Explanation:
- Sample Dictionary: A dictionary named
input_dict is defined with some key-value pairs. Two of the values contain spaces.
- Existing Output Array: An list named
output_array is initialised with some existing key-value pairs.
- Loop Through Dictionary:
- The
for loop iterates over the dictionary using the .items() method, which returns both the key and value for each iteration.
- During each iteration
key contains the current key and value contains the corresponding value.
- The
if ' ' in value: condition checks if there is a space in the value.
- If the condition is
True, the append method is used to add a tuple (key, value) to the output_array.
- Print Output Array: The contents of
output_array are printed, showing the updated list of tuples. It includes the initial values as well as the new key-value pairs where the value contains a space.
Using List Comprehension
You can also achieve the same result more concisely using a list comprehension and then extending the existing list:
# Sample dictionary
input_dict = {
'key1': 'value1',
'key2': 'value with space',
'key3': 'another value with space',
'key4': 'nospacevalue',
}
# Existing output array with some initial values
output_array = [('existing_key1', 'existing_value1'), ('existing_key2', 'existing_value2')]
# Extract key-value pairs where the value contains a space using list comprehension
new_pairs = [(key, value) for key, value in input_dict.items() if ' ' in value]
# Extend the existing output array with the new key-value pairs
output_array.extend(new_pairs)
# Print the updated output array
print(output_array)