python字典生成式格式_如何用双引号创建一个Python字典作为默认报价格式?

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.

解决方案

You can construct your own version of a dict with special printing using json.dumps():

>>> import json

>>> class mydict(dict):

def __str__(self):

return json.dumps(self)

>>> couples = [['jack', 'ilena'],

['arun', 'maya'],

['hari', 'aradhana'],

['bill', 'samantha']]

>>> pairs = mydict(couples)

>>> print pairs

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

You can also iterate:

>>> for el in pairs:

print el

arun

bill

jack

hari

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值