0

Is it possible to obtain a python dictionary where the keys are wrapped within " " as opposed to ' '?

Something like this:

{"key_1":"value_1", .... , "key_n":"value_n"}

instead of:

{'key_1':'value_1', .... , 'key_n':'value_n'}
devnull
  • 118,548
  • 33
  • 236
  • 227
steve
  • 594
  • 4
  • 10
  • 23

5 Answers5

3

Well, it kind of looks like you want JSON formatting instead... so maybe:

>>> d = {"key_1":"value_1", "key_n":"value_n"}
>>> d
{'key_n': 'value_n', 'key_1': 'value_1'}
>>> import json
>>> json.dumps(d)
'{"key_n": "value_n", "key_1": "value_1"}'
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

Yes. Quotes are completely interchangeable; you can define a dictionary with either. You can also use triple quotes ''' and """.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
1

The simplest way to force the use of double quotes in the string representation of a dictionary would be to convert the dictionary to json. That does however lose some type information as (for example) numeric keys will also be enclosed in double quotes:

>>> d = {'key_1':'value_1', 'key_n':'value_n'}
>>> import json
>>> json.dumps(d)
'{"key_1": "value_1", "key_n": "value_n"}'
>>> json.dumps({1:'a', 2:'b'})
'{"1": "a", "2": "b"}'

If the reason you wanted double quotes was to use the resulting string for JSON then this is the answer you want. If on the other hand the requirement really was just to force double quotes for display but otherwise keep it as a dictionary then the best you can do may be to write your own conversion code.

Duncan
  • 92,073
  • 11
  • 122
  • 156
  • In my case I obtain the following using json.dumps : {u'key':u'value'} – steve Oct 14 '13 at 14:19
  • @steve, which version of Python and are you sure there isn't another module called `json` hiding the system one? That isn't valid json so if you're getting that your json module seems to be very broken. – Duncan Oct 14 '13 at 14:53
  • It's the python incorporated within Splunk ( http://dev.splunk.com/ ) . How can one directly and explicitly reference a particular module ? ..like "java.lang.String" – steve Oct 15 '13 at 07:37
0

Yes unless you have quotes inside the string. single and double quotes are the same BUT

if one of my keys for some reason was I don't know: "Isn't" I would use double quotes. If there's a chance my keys will have double quotes I would use single quotes.

Edit: I'm not saying it's right or wrong to have quotes inside the key identifiers I'm just saying it's something to consider if that's the reality you are facing.

mlnyc
  • 2,636
  • 2
  • 24
  • 29
0

If you want to print the dictionary you can use this snippet

print "{%s}" % ", ".join('"%s":"%s"' % pair for pair in D.items())
OdraEncoded
  • 3,064
  • 3
  • 20
  • 31