问题描述
我正在尝试创建一个 python 字典,该字典将用作 html 文件中的 java 脚本 var 用于可视化目的.作为必要条件,我需要使用双引号内的所有名称创建字典,而不是 Python 使用的默认单引号.有没有一种简单而优雅的方法来实现这一点.
情侣 = [['杰克', '伊莲娜'],['阿伦','玛雅'],['hari', 'aradhana'],['比尔','萨曼莎']]对 = 字典(夫妇)打印对
生成的输出:
{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}
预期输出:
{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"}
我知道,json.dumps(pairs)
可以完成这项工作,但是字典作为一个整体被转换为一个字符串,这不是我所期望的.
P.S.: 是否有使用 json 的替代方法,因为我正在处理嵌套字典.
您可以使用 json.dumps()
构建您自己的具有特殊打印功能的 dict 版本:
你也可以迭代:
>>>对于 el 成对:打印电子阿伦账单杰克哈里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
这篇关于如何使用双引号作为默认引号格式创建 Python 字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!