Python Practice › Dictionary Programs › Program 93
Reverse values and decorate keys
Write a Python program to reverse each string value and put underscores around each key.
Input
{"a": "Python", "b": "Programming", "c": "Learning"}Output
{'_a_': 'nohtyP', '_b_': 'gnimmargorP', '_c_': 'gninraeL'}Approach
- Dict comprehension with an f-string key and
[::-1]value.
Solution
d = {"a": "Python", "b": "Programming", "c": "Learning"}print({f"_{k}_": v[::-1] for k, v in d.items()})Output
{'_a_': 'nohtyP', '_b_': 'gnimmargorP', '_c_': 'gninraeL'}Learn the concept
New to this topic? Read the lesson, then come back.