100

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

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

生成的输出:

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

预期输出:

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

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

PS:是否有使用 json 的替代方法,因为我正在处理嵌套字典。

4

7 回答 7

81

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

>>> 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"}
于 2013-08-17T00:02:27.547 回答
69

您可以使用以下命令构建您自己的带有特殊打印的 dict 版本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"}

您还可以迭代:

>>> for el in pairs:
       print el

arun
bill
jack
hari
于 2013-08-17T00:28:20.643 回答
12
# 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 = [
           ['jack', 'ilena'], 
           ['arun', 'maya'], 
           ['hari', 'aradhana'], 
           ['bill', 'samantha']]
pairs = doubleQuoteDict(couples)
print pairs

产量:

{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"}
于 2013-08-17T00:27:19.577 回答
7

这是一个基本print版本:

>>> print '{%s}' % ', '.join(['"%s": "%s"' % (k, v) for k, v in pairs.items()])
{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"}
于 2013-08-17T00:10:35.053 回答
4

问题的前提是错误的:

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.

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

当 Python 看到:

print somedict

它真正的作用是:

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

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

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

后记仍然没有抓住重点:

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

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

于 2015-06-12T15:56:36.960 回答
1

很简单只需2步

step1:converting your dict to list

step2:iterate your list and convert as json .

为了更好地理解下面的片段

import json
couples = [
               ['jack', 'ilena'], 
               ['arun', 'maya'], 
               ['hari', 'aradhana'], 
               ['bill', 'samantha']]
pairs = [dict(couples)]#converting your dict to list
print(pairs)

#iterate ur list and convert as json
for x in pairs:
    print("\n after converting: \n\t",json.dumps(x))#json like structure
于 2020-10-16T13:03:35.017 回答
1

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

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.

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

<class 'dict'> {'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana', 'arun': 'maya'}
{"bill": "samantha", "jack": "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.

with open('json_test.json', 'r') as f:
    json_string = f.read()
    print(json_string)
于 2016-09-07T21:46:41.757 回答