Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dictionary into string

Tags:

python

string

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

like image 407
TechacK Avatar asked May 06 '12 18:05

TechacK


People also ask

How do I change a dictionary to a string?

To convert a dictionary to string in Python, use the json. dumps() function. The json. dumps() is a built-in function in json library that can be used by importing the json module into the head of the program.

Can we convert string to dictionary in Python?

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.

How do you convert a key to a string in Python?

Use str() and dict. items() to convert dictionary keys and values to strings.


2 Answers

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()))
like image 187
gnr Avatar answered Oct 07 '22 01:10

gnr


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'

like image 26
shibly Avatar answered Oct 07 '22 02:10

shibly