1

What is the easiest way to convert Python dict e.g.:

a = {'a': 'value', 'b': 'another_value', ...}

into string using user format e.g.:

'%s - %s\n'

so it gives me:

a - value
b - another_value

This works, but maybe there is something shorter/better using map (without iterating over collection)

''.join(['%s %s\n' % o for o in a.items()])
2
  • There's no need for that list, just do: '\n'.join('%s %s' % o for o in a.items()) Commented Jan 17, 2012 at 11:56
  • map still iterates over the collection, it just happens that sometimes it is faster and sometimes slower than an explicit loop. Commented Jan 17, 2012 at 13:23

2 Answers 2

5

I'd write this as:

>>> print '\n'.join(' '.join(o) for o in a.items())
a value
b another_value

Or:

>>> print '\n'.join(map(' '.join, a.items()))
a value
b another_value
Sign up to request clarification or add additional context in comments.

2 Comments

I may be reading the question wrong, but to me "using user format" suggests that the format string is essentially a parameter.
YES. Joining string is a parameter, so I could create function def dict_to_str(dict_obj, join_str_format)
2

You can omit the square brackets to avoid building the intermediate list:

''.join('%s %s\n' % o for o in a.items())

Since you're asking about map, here is one way to write it using map:

''.join(map(lambda o:'%s %s\n' % o, a.items()))

It's a matter of preference, but I personally find it harder to read than the original version.

2 Comments

map when using lambda is almost certainly slower than just using for. Of course you can avoid the lambda here but then it is definitely harder to read: ''.join(map('%s %s\n'.__mod__, a.items()))
I just thought there is shorter version without iterating over list, but I see this first version is simply what I need :) Thank You.

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.