views:

441

answers:

5

EDIT: Clarified the question a bit

How can I get a string from a dictionary with the format

key1 = value1
key2 = value2

in a relatively fast way ? (relative to plain concatenation)

+2  A: 

Like this:

DATA = {'key1': 'value1', 'key2': 'value2'}
print "\n".join(sorted(["%s = %s" % (k,v) for (k,v) in DATA.iteritems()]))
RichieHindle
+2  A: 
print '\n'.join('%s = %s' % (key, value) for key, value in d.iteritems())
Nadia Alramli
+3  A: 

There's no reason to use list comprehension here.

Python 3.x:

for k,v in mydict.items():
  print(k, '=', v)

Python 2.x:

for k,v in mydict.iteritems():
  print k, '=', v

EDIT because of comment by OP in another answer:

If you're passing it to a function and not printing it here, then you should just pass the generator to the function, or the dict itself and let the function handle whatever it needs to do with it.

This is much better than converting it to a string inside a namespace where it's not even needed. The function should do that, since that's where it's used.

I made a wrapper function, since editing the main function is out of the question.

def log_wrap(mydict):
    mystr = '\n'.join(['%s = %s' % (k,v) for k,v in mydict.iteritems()])
    write_to_log(mydict)

log_wrap(mydict)
Tor Valamo
I don't see any namespaces here. Did you mean "scope"?
Pavel Minaev
The function I am passing it to is from a logging module that I cannot change.
TP
@Pavel - yes i did. :P @Jaelebi - So you're passing the same string to the same logging function several times? why?
Tor Valamo
@Jaelebi - Either way you should probably wrap it like my edit says, so as to leave the rest of the code 'clean'.
Tor Valamo
im passing it several times since I have a loop that iterates over messages(in binary files) and which it then converts to a dictionary and does quite a lot of other stuff. Each of the messages have to be logged in a human readable format then
TP
So the logging only happens once for each dictionary?
Tor Valamo
yes.........................................
TP
Then why not put it in a wrapper function that handles the formatting? See my edit now.
Tor Valamo
+2  A: 

Explicit is better than implicit: list comprehension is a way to create list, not to avoid loops.
From PEP 202:

List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used.

What is the usefulness to create such kind of code in python?
It is more compact, and so? Given that code is read much more times than it is written, what is the advantage in it?
Tor Valamo's solution, although not what asked in original request, is in my opinion far more readable, and therefore to prefer.

EDIT after question update
Join is a good way to implement a fast concatenation from a list - and replies from Nadia and Ritchie are good examples of how to use it.
Again, I would not perform everything in a single line, but I would split it in various steps to empathize readability.

Roberto Liffredo
I undeleted my answer after a little edit. I looped it as a tupled list at first, so it was wrong.
Tor Valamo
I wanted this method since I want to pass the complete string to a function. In case of directly looping, I would have to concatenate it or use a stringIO function. And I need to do this a LOT of times
TP
Your question says "How can I print out a dictionary with the format ..." And that's what we've answered. If you need it for something else then you should explain that scenario, as there are probably other optimisations for that too.
Tor Valamo
A: 

I prefer the pythonic way:

mydict = {'a':1, 'b':2, 'c':3}
for (key, value) in mydict.items():
    print key, '=', value
enrnpfnfp
mydict.iteritems() would be better for huge dicts
bgbg