15

I'm trying to use the solution provided here

Instead of getting a dictionary, how can I get a string with the same output i.e. character followed by the number of occurrences

Example:d2m2e2s3

Community
  • 1
  • 1
TechacK
  • 165
  • 1
  • 1
  • 7

5 Answers5

47

To convert from the dict to the string in the format you want:

''.join('{}{}'.format(key, val) for key, val in adict.items())

if you want them alphabetically ordered by key:

''.join('{}{}'.format(key, val) for key, val in sorted(adict.items()))
gnr
  • 2,324
  • 1
  • 22
  • 24
3

Is this what you are looking for?

#!/usr/bin/python

dt={'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
st=""
for key,val in dt.iteritems():
    st = st + key + str(val)

print st

output: q5w3d2g2f2

Or this?

#!/usr/bin/python

dt={'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
dt=sorted(dt.iteritems())
st=""

for key,val in dt:
    st = st + key + str(val)

print st

output: d2f2g2q5w3

Example with join:

#!/usr/bin/python

adict=dt={'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
' '.join('{0}{1}'.format(key, val) for key, val in sorted(adict.items()))

output: 'd2 f2 g2 q5 w3'

cola
  • 12,198
  • 36
  • 105
  • 165
1

Once you have the dict solution, just use join to join them into a string:

''.join([k+str(v) for k,v in result.iteritems()])

You can replace the '' with whatever separater (including none) you want between numbers

happydave
  • 7,127
  • 1
  • 26
  • 25
1
>>> result = {'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
>>> ''.join('%s%d' % (k,v) for k,v in result.iteritems())
'q5w3d2g2f2'

or if you want them alphabetically...

>>> ''.join('%s%d' % (k,v) for k,v in sorted(result.iteritems()))
'd2f2g2q5w3'

or if you want them in increasing order of count...

>>> ''.join('%s%d' % (k,v) for k,v in sorted(result.iteritems(),key=lambda x:x[1]))
'd2g2f2w3q5'
Amber
  • 507,862
  • 82
  • 626
  • 550
-1

Another approach, avoiding the % interpolation (or format()) by using join() only:

''.join(''.join((k, str(v))) for k,v in mydict.items())
MestreLion
  • 12,698
  • 8
  • 66
  • 57