Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

How to create a Python dictionary with double quotes as default quote format?

I am trying to create a python dictionary which is to be used as a java script var inside a html file for visualization purposes. As a requisite, I am in need of creating the dictionary with all names inside double quotes instead of default single quotes which Python uses. Is there an easy and elegant way to achieve this.

    couples = [
               ['jack', 'ilena'], 
               ['arun', 'maya'], 
               ['hari', 'aradhana'], 
               ['bill', 'samantha']]
    pairs = dict(couples)
    print pairs

Generated Output:

{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}

Expected Output:

{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"}

I know, json.dumps(pairs) does the job, but the dictionary as a whole is converted into a string which isn't what I am expecting.

P.S.: Is there an alternate way to do this with using json, since I am dealing with nested dictionaries.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

json.dumps() is what you want here, if you use print json.dumps(pairs) you will get your expected output:

>>> pairs = {'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}
>>> print pairs
{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}
>>> import json
>>> print json.dumps(pairs)
{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...