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'}
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'}
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"}'
Yes. Quotes are completely interchangeable; you can define a dictionary with either. You can also use triple quotes '''
and """
.
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.
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.
If you want to print the dictionary you can use this snippet
print "{%s}" % ", ".join('"%s":"%s"' % pair for pair in D.items())