0

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?

3
  • 2
    n_temp_new is a string, not a dict, because json.dumps returns a string representation of a dict. You probably wanted to compare g_temp with n_temp['giorno']. Commented May 10, 2018 at 9:05
  • yes! now it works! sorry but i'm new with promgramming. thanks ;) Commented May 10, 2018 at 9:07
  • In fact, you don't need the n_temp_new = json.dumps(n_temp, ensure_ascii=False) at all. Commented May 10, 2018 at 11:56

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.