Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
比较Python中的两个json字典_Python_Json - Fatal编程技术网

比较Python中的两个json字典

比较Python中的两个json字典,python,json,Python,Json,我想比较两本字典。一个是模板,另一个存储在特定文件中 代码如下: #!/usr/bin/env python import json template = {"giorno": 21, "mese": "aprile", "ora": "21"} newww = "palestra.json" g_temp = template['giorno'] with open(newww, 'r') as f: n_temp = json.load(f) pri

我想比较两本字典。一个是模板,另一个存储在特定文件中

代码如下:

#!/usr/bin/env python

import json

template = {"giorno": 21, "mese": "aprile", "ora": "21"}
newww = "palestra.json"


g_temp = template['giorno']

with open(newww, 'r') as f:
        n_temp = json.load(f)
        print n_temp
        n_temp_new = json.dumps(n_temp, ensure_ascii=False)
        print(n_temp_new)

if g_temp == n_temp_new['giorno']:
        print("no")
else:
        print("yes")
palestra.json:

{"giorno": 21, "mese": "aprile", "ora": "21"}
输出:

{u'giorno': 21, u'mese': u'aprile', u'ora': u'21'}
{"giorno": 21, "mese": "aprile", "ora": "21"}
Traceback (most recent call last):
  File "./prova.py", line 25, in <module>
    if g_temp == n_temp_new['giorno']:
TypeError: string indices must be integers
{u'giorno':21,u'mese':u'aprile',u'ora':u'21'}
{“giorno”:21,“mese”:“aprile”,“ora”:“21”}
回溯(最近一次呼叫最后一次):
文件“/prova.py”,第25行,在
如果g_temp==n_temp_new['giorno']:
TypeError:字符串索引必须是整数

如何比较这两个词典?

发生错误的原因是
n\u temp\u new
是字符串,而不是dict,因此不允许对字符串进行索引。请注意,
json.dumps
返回dict的字符串表示形式,但不返回dict本身

您可能想将
g_temp
n_temp['giorno']
进行如下比较:

if g_temp == n_temp['giorno']:
    print('no')
else:
    print('yes')

n_temp\u new
是一个字符串,而不是dict,因为
json.dumps
返回dict的字符串表示形式。您可能想将
g_temp
n_temp['giorno']
进行比较。是的!现在它工作了!对不起,我是新来的。谢谢;)事实上,您根本不需要
n_temp\u new=json.dumps(n_temp,确保ascii=False)