如何使用双引号作为默认引号格式创建 Python 字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18283725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:23:53  来源:igfitidea点击:

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

pythonpython-2.7dictionarypython-3.x

提问by Shankar

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.

我正在尝试创建一个 python 字典,该字典将用作 html 文件中的 java 脚本 var 用于可视化目的。作为必要条件,我需要使用双引号内的所有名称创建字典,而不是 Python 使用的默认单引号。有没有一种简单而优雅的方法来实现这一目标。

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

Generated Output:

生成的输出:

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

Expected Output:

预期输出:

{"arun": "maya", "bill": "samantha", "Hyman": "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.

我知道,可以json.dumps(pairs)完成这项工作,但是字典作为一个整体被转换为一个字符串,这不是我所期望的。

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

PS:有没有其他方法可以使用 json 来做到这一点,因为我正在处理嵌套字典。

采纳答案by elyase

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

您可以使用以下方法构建您自己的具有特殊打印功能的 dict 版本json.dumps()

>>> import json
>>> class mydict(dict):
        def __str__(self):
            return json.dumps(self)

>>> couples = [['Hyman', 'ilena'], 
               ['arun', 'maya'], 
               ['hari', 'aradhana'], 
               ['bill', 'samantha']]    

>>> pairs =  mydict(couples) 
>>> print pairs
{"arun": "maya", "bill": "samantha", "Hyman": "ilena", "hari": "aradhana"}

You can also iterate:

您还可以迭代:

>>> for el in pairs:
       print el

arun
bill
Hyman
hari

回答by Andrew Clark

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

json.dumps()是你想要的,如果你使用,print json.dumps(pairs)你会得到预期的输出:

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

回答by Brent Washburne

Here's a basic printversion:

这是一个基本print版本:

>>> print '{%s}' % ', '.join(['"%s": "%s"' % (k, v) for k, v in pairs.items()])
{"arun": "maya", "bill": "samantha", "Hyman": "ilena", "hari": "aradhana"}

回答by Russell Borogove

# do not use this until you understand it
import json

class doubleQuoteDict(dict):
    def __str__(self):
        return json.dumps(self)

    def __repr__(self):
        return json.dumps(self)

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

Yields:

产量:

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

回答by Raymond Hettinger

The premise of the question is wrong:

问题的前提是错误的:

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.

You should be expecting a conversion to a string. All "print" does is convert an object to a string and send it to standard output.

您应该期待转换为字符串。“打印”所做的只是将对象转换为字符串并将其发送到标准输出。

When Python sees:

当 Python 看到:

print somedict

What it really does is:

它的真正作用是:

sys.stdout.write(somedict.__str__())
sys.stdout.write('\n')

As you can see, the dict is always converted to a string (afterall a string is the only datatype you can send to a file such as stdout).

如您所见,dict 总是被转换为字符串(毕竟字符串是您可以发送到诸如stdout 之类的文件的唯一数据类型)。

Controlling the conversion to a string can be done either by defining __str__ for an object (as the other respondents have done) or by calling a pretty printing function such as json.dumps(). Although both ways have the same effect of creating a string to be printed, the latter technique has many advantages (you don't have to create a new object, it recursively applies to nested data, it is standard, it is written in C for speed, and it is already well tested).

可以通过为对象定义 __str__(正如其他受访者所做的那样)或调用漂亮的打印函数(例如json.dumps(). 虽然两种方式创建要打印的字符串效果相同,但后一种技术有很多优点(你不必创建新对象,它递归地应用于嵌套数据,它是标准的,它是用 C 编写的,用于速度,并且已经过良好测试)。

The postscript still misses the point:

后记仍然没有抓住要点:

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

Why work so hard to avoid the jsonmodule? Pretty much any solution to the problem of printing nested dictionaries with double quotes will re-invent what json.dumps()already does.

为什么要如此努力地避免使用json模块?几乎任何解决用双引号打印嵌套字典的问题都会重新发明json.dumps()已经做了什么。

回答by shao.lo

The problem that has gotten me multiple times is when loading a json file.

我多次遇到的问题是加载 json 文件时。

import json
with open('json_test.json', 'r') as f:
    data = json.load(f)
    print(type(data), data)
    json_string = json.dumps(data)
    print(json_string)

I accidentally pass data to some function that wants a json string and I get the error that single quote is not valid json. I recheck the input json file and see the double quotes and then scratch my head for a minute.

我不小心将数据传递给某个需要 json 字符串的函数,我得到了单引号不是有效 json 的错误。我重新检查了输入的 json 文件,看到了双引号,然后挠了挠头一分钟。

The problem is that data is a dict not a string, but when Python converts it for you it is NOT valid json.

问题是 data 是一个 dict 而不是字符串,但是当 Python 为你转换它时,它不是有效的 json。

<class 'dict'> {'bill': 'samantha', 'Hyman': 'ilena', 'hari': 'aradhana', 'arun': 'maya'}
{"bill": "samantha", "Hyman": "ilena", "hari": "aradhana", "arun": "maya"}

If the json is valid and the dict does not need processing before conversion to string, just load as string does the trick.

如果 json 有效并且 dict 在转换为字符串之前不需要处理,只需按字符串加载即可。

with open('json_test.json', 'r') as f:
    json_string = f.read()
    print(json_string)