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…
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'
An attempt:
s = ''
for k, v in dct.items():
s += k + ' ' + str(v) + ' '
# remove the last character, an unnecessary space
s = s[:-1]
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'
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'
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…
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'
An attempt:
s = ''
for k, v in dct.items():
s += k + ' ' + str(v) + ' '
# remove the last character, an unnecessary space
s = s[:-1]
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'
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'