Reputation: 29
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?
Upvotes: 0
Views: 196
Reputation: 3138
The error occurs because n_temp_new
is a string, not a dict and thus does not allow string indexing. Note that json.dumps
returns a string representation of a dict but not a dict itself.
You probably wanted to compare g_temp
with n_temp['giorno']
like this:
if g_temp == n_temp['giorno']:
print('no')
else:
print('yes')
Upvotes: 1