concatenate key value pairs from python dictionary

Question:

I have a dictionary in python. The keys and the values are both strings. In fact the keys are some kind of flag (like -f) and the values are the options (e.g. an int like 20). What I want to do is to create a string with all the keys and values.
The dictionary could look something like this:
{'-f': 20, '-d': 30} and what I would like is something like this:
"-f 20 -d 30"
I think this should be any easy task, but I couldn’t find a solution until now…

Asked By: Robin Kohrs

||

Answers:

Here’s one approach using a list comprehension:

d = {'-f': 20, '-d': 30}
' '.join([i for k,v in d.items() for i in [k, str(v)]])
# '-f 20 -d 30'

Which is equivalent to:

out = []
for k,v in d.items():
    for i in [k, str(v)]:
        out.append(i)

' '.join(out)
# '-f 20 -d 30'
Answered By: yatu

An attempt:

s = ''
for k, v in dct.items(): 
    s += k + ' ' + str(v) + ' '
    # remove the last character, an unnecessary space
    s = s[:-1] 
Answered By: DimK

you could use str.join with generator expression:

d = {'-f': 20, '-d': 30}

' '.join(str(e) for t in d.items() for e in t)
# '-f 20 -d 30'
Answered By: kederrac

Based on yatu answer but with f-strings you could do :

d = {'-f': 20, '-d': 30}
' '.join([f"{k} {v}" for k,v in d.items()])`
# '-f 20 -d 30' 
Answered By: TmSmth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.