I want to compare two dictionaries. One is a template, and one is stored in a specific file.
The code is this:
#!/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"}
output:
{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
How can I compare these two dictionaries?
n_temp_newis a string, not a dict, becausejson.dumpsreturns a string representation of a dict. You probably wanted to compareg_tempwithn_temp['giorno'].n_temp_new = json.dumps(n_temp, ensure_ascii=False)at all.