ledien
ledien

Reputation: 549

Convert Dictionary to String

I have

  dic = {'value': '123','sort': 'desc','type': 'float'} 

I want it become string like:

 str = 'value=123&sort=desc&type=float'

How can I do it?

Thanks

Upvotes: 0

Views: 2691

Answers (4)

greole
greole

Reputation: 4771

This wont work with dictionaries if you care about the order of the string elements since the items are not stored in a specific order. Use OrderedDict instead.

Unless the resulting string has always the same format so you could use the format notation

>>> dic={'value':'123','sort':'desc','type':'float'} 
>>> str='value={value}&sort={sort}&type={type}'.format(**dic)

Upvotes: 1

Oni1
Oni1

Reputation: 1505

dic={'value':'123','sort':'desc','type':'float'}     
str=''
for i in dic:
    str = str + i + '=' + dic[i] + '&'
str[:-1]

Or with list comprehension and reduce:

reduce(lambda x,y: x+y, [i+'='+dic[i]+'&' for i in dic])[:-1]

Upvotes: -3

Jimmy Kane
Jimmy Kane

Reputation: 16865

Can also be done with urllib

import urllib
d = {'value':'123','sort':'desc','type':'float'}
urllib.urlencode(d)
'sort=desc&type=float&value=123'

Upvotes: 6

James Mills
James Mills

Reputation: 19050

Like this:

>>> d = {'value':'123','sort':'desc','type':'float'}
>>> "&".join(["{}={}".format(k, v) for k, v in d.items()])
'sort=desc&type=float&value=123'
>>> 

As pointed out in many of the comments; if this is for a HTTP Request, use the urllib.urlencode function.

>>> from urllib import urlencode
>>> urlencode(d)
'sort=desc&type=float&value=123'
>>> 

Upvotes: 7

Related Questions