Formatting the keys and values in a dictionary into a list of strings

39 views Asked by At

I have a dictionary that looks like this:

{'name': 'Frank', 'job': 'coder', 'quality': 'just ok'}

I want to create a list using .format that creates a list like this:

["name(Frank)", "job(coder)", "quality(just ok)"]

I was hoping I could use a {key}({value}).format(**dictionary) kind of thing but I can't figure out how to do it. Do I have to loop with each entry to create the list?

1

There are 1 answers

0
Andrej Kesely On

Use list-comprehension and an f-string for the task:

dct = {'name':'Frank', 'job' : 'coder', 'quality' : 'just ok'}

lst = [f'{k}({value})' for k, v in dct.items()]
print(lst)

Prints:

['name(Frank)', 'job(coder)', 'quality(just ok)']