0

Let's say I have something like this:

counts = {"chuck" : 1 , "annie" : 42, "jan" : 100}
lst = list(counts.keys())
lst.sort()
for key in lst:
    print(key, counts[key])

The output would be

chuck 1
annie 42
jan 100

If I wanted to achieve this effect with a string, the string would be represented as

"chuck 1\nannie 42\njan 100\n"

Now if I wanted to accomplish this string I could try something like:

for key, value in counts.items():
    if value == 1:
        counts[key] = "1\n"
    elif value == 42:
        counts[key] = "42\n"
    elif value == 100:
        counts[key] = "100\n"

temp = list(counts.items())
temp.sort()
myStr = str(temp)

for char in myStr:
    if char in "[(',)]":
        myStr = myStr.replace(char,'')

finalStr = "" + myStr[0:19] + "" + myStr[20:37] + "" + myStr[38:53] + ""

But yeah, I think I'm overcomplicating things... What would be a better and easy way?

Thanks!

Riggs
  • 99
  • 2
  • 9

5 Answers5

2

You can achieve this by formatting each key, value as the string you expect per "{} {}".format(key, value)

Then, join on '\n':

"\n".join(["{} {}".format(key, value) for key, value in counts.items()])

Demo:

Input:

counts = {"chuck" : 1 , "annie" : 42, "jan" : 100}

Output:

jan 100
chuck 1
annie 42

Noticed that sorted was a requirement, so here it is with a sort:

"\n".join(["{} {}".format(key, value) for key, value in sorted(counts.items())])

output:

annie 42
chuck 1
jan 100
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • Great minds think alike ... at approximately the same speed, too. :) I believe that it is more efficient to use a list comprehension with `.join()` rather than a generator expression. – zondo Apr 01 '16 at 19:39
  • So far, just about every answer that uses a generator expression gets the comment. From what I've read, it's because `.join()` needs to know how much memory to allocate, so it converts the generator to a list anyway. Of course, it would be more efficient to skip the generator part and just go straight to the list. – zondo Apr 01 '16 at 19:43
  • Interesting. Thanks for the info. – idjaw Apr 01 '16 at 19:44
  • @zondo Indeed, on this particular example, `%timeit` says 2.4 µs vs. 3.24 µs in favor of list comprehension. I'm not sure if that's not premature optimization, though. BTW, using `*item` to unpack instead of `key, value`, seems to be marginally slower. – arekolek Apr 01 '16 at 19:52
  • Awesome. Thanks for checking that @arekolek – idjaw Apr 01 '16 at 19:52
  • @zondo Here is the answer to comprehension vs. expression. It's great. Thought I'd share: http://stackoverflow.com/a/9061024/1832539 – idjaw Apr 06 '16 at 03:43
  • @idjaw: Thanks. I'll be sure to use that link in the future. – zondo Apr 06 '16 at 10:30
1

Concise with sorting:

>>> '\n'.join(sorted([k+' '+str(v) for k, v in counts.items())])
'annie 42\nchuck 1\njan 100'

Sorting lines instead of items. It's actually faster this way as measured by %timeit.

arekolek
  • 9,128
  • 3
  • 58
  • 79
0

It's a bit clunky:

'\n'.join(["{0} {1}".format(a,b) for a,b in counts.items()])
Josh English
  • 512
  • 2
  • 16
0

If you're going for concise.

d = {"chuck" : 1 , "annie" : 42, "jan" : 100}

'\n'.join('{} {}'.format(*item) for item in sorted(d.items()))
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36
-1
d = {"chuck" : 1 , "annie" : 42, "jan" : 100};
s = '\n'.join(['%s %s' % (key, value) for (key, value) in sorted(d.items(), key=lambda x: x[1])])
print(s) # 'chuck 1\nannie 42\njan 100'

d = {"chuck" : 1 , "annie" : 42, "jan" : 100};
s = '\n'.join(['%s %s' % (key, value) for (key, value) in sorted(d.items(), key=lambda x: x[0])])
print(s) # 'annie 42\nchuck 1\njan 100'
Maciej A. Czyzewski
  • 1,539
  • 1
  • 13
  • 24
  • I really like this one. Thanks @Maciej A. Czyzewski – Riggs Apr 01 '16 at 19:50
  • @MaciejA.Czyzewski How did I not see that! :) OK. Thanks! (btw. I did not downvote you...) – idjaw Apr 01 '16 at 20:00
  • You don't need to use the list comprehension, a generator expression with work the same without the braces. Also, `operator.itemgetter` could be used instead of the `lambda` function. Finally, `format` is generally preferred over `%` substitution. – Jared Goguen Apr 01 '16 at 20:09