简体   繁体   中英

concatenate items in dictionary in python using list comprehension

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)

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 scope 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)
print '\n'.join('%s = %s' % (key, value) for key, value in d.iteritems())

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.

So you should ask yourself:
When is it useful to create this code in Python? It may be more compact but code is read many more times than it is written so what is the advantage in it?

Tor Valamo's solution, although not what was asked for in the original request, is in my opinion far more readable, and therefore should be preferred .

EDIT after question update
str.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 emphasize readability.

Like this:

DATA = {'key1': 'value1', 'key2': 'value2'}
print "\n".join(sorted(["%s = %s" % (k,v) for (k,v) in DATA.iteritems()]))

I prefer the pythonic way:

mydict = {'a':1, 'b':2, 'c':3}
for (key, value) in mydict.items():
    print key, '=', value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM