1

I have a dict that looks something like this:

d = {'a': 'b', 'c': 'd'}

Now, when I make a str out of it using str(d) i get

>> "{'a': 'b', 'c': 'd'}"

but I need it to look like this:

>> "a=b; c=d; " 

I created this piece of code that does this:

b = ''
for k, v in d.items():
    b += str(k) + '=' + str(v) + '; '

Is there a way to achieve the same effect, but doing it with an inline operation or some other neater way, without using the for loop?

1
  • For higher performance you could use: ''.join() Commented Feb 25, 2019 at 19:46

4 Answers 4

4

Her is another way using ''.join():

';'.join(map('='.join, d.items()))

Returns:

'a=b;c=d'

This assumes the last ; is redundant. If not you could get the "exact" output as this: ''.join([f'{k}={v}; ' for k,v in d.items()])


Timings:

%timeit ';'.join(map('='.join, d.items()))          #1000000 loops,best of 3: 810 ns per loop
%timeit ';'.join(['='.join(x) for x in d.items()])  #1000000 loops,best of 3: 956 ns per loop
%timeit ';'.join([f'{k}={v}' for k,v in d.items()]) #1000000 loops,best of 3: 872 ns per loop
Sign up to request clarification or add additional context in comments.

2 Comments

you don't need those square brackets
@WalterTross True, but the ''.join() will convert it to a list before operating anyway. Try using %timeit and you might be surprised as the [] is actually quicker.
3

Like this:

d = {'a': 'b', 'c': 'd'}
strd = " ".join("{}={};".format(x, y) for x, y in d.iteritems()) # items() if python3

strd:

"a=b; c=d;"

Comments

1

If you're not too attached with = sign, you can convert it into a json string

import json

json.dumps({'a': 'b', 'c': 'd'})

This would work for nested dictionaries as well.

Comments

0

You can use the magic method __repr__() to get the string representation of an object:

d = {'a': 'b', 'c': 'd'}

d.__repr__()
# {'a': 'b', 'c': 'd'}

d.__repr__().replace(': ', '=').strip('{}')
# 'a'='b', 'c'='d'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.