Dictionary to String
Description
The dictionary_to_string
function converts a dictionary into a human-readable string, where each key-value pair is formatted as key: value
and sorted alphabetically by key.
Function Signature:
def dictionary_to_string(dictionary: dict) -> str:
Parameters
- dictionary (
dict
): The dictionary to be converted into a string.
Returns
- str: A string representation of the dictionary where each key-value pair is printed in the format
key: value
on a new line.
Example Usage
my_dict = {'b': 2, 'a': 1, 'c': 3}
result = dictionary_to_string(my_dict)
print(result)
Example Output:
a: 1
b: 2
c: 3
Code
def dictionary_to_string(dictionary: dict) -> str:
result = ''
try:
sorted_keys = sorted(dictionary.keys())
for key in sorted_keys:
result += f"{key}: {dictionary[key]}\n"
except Exception as ex:
filename, line_number = get_exception_info()
return result
Notes
- This function sorts the dictionary keys alphabetically before converting them into a string representation.
- It uses Python's built-in
sorted()
function to get the keys in order and then formats the output. - If an exception occurs, the function will catch it but currently does not print any error details. You can uncomment the error handling code to print exception details.
Error Handling
- If an error occurs while processing the dictionary (e.g., an invalid input), the exception is caught, but no error message is printed (as the print statements in the exception block are commented out). The function will return an empty string in case of any issues.