Ritzor
Ritzor

Reputation: 665

Python: Getting error while manipulating dictionary and JSON (string indices must be integers, not unicode)

My code is as follows Contents of dict1 and dict 2 are printed below in output This code is part of my program in which dict1 and dict2 are generated by program only and fed as input to this piece of code.
When I just run bellow fragment of code as a separate program by explicitly declaring dict1 and dict2 it works perfectly. While when I use this code fragment in my program where dict1 and dict2 auto generated it throws error as given in output.
Note:
The program creates new dict with K(value of dict2):v(value of dict1) where keys of both dict same.

print dict1
print dict2
def walk(dict1, dict2):
    output = {}
    for key, value in dict1.iteritems():
        if isinstance(value, dict):
            output[dict2[key]] = walk(value, dict2)
        else:
            output[dict2[key]] = value
    return output


output = walk(dict1, dict2)
print output

Output is:

{u'one': u'ele-ven', u'-two': u'twe.lve'}    #This is dict1
{"one": "red", "two": "blue"}                   # this is dict2
Traceback (most recent call last):
File "z.py", line 68, in <module>
output = walk(my_data, dictionary)
File "z.py", line 62, in walk
output[dict2[key]] = walk(value, dict2)
File "z.py", line 64, in walk
output[dict2[key]] = value
TypeError: string indices must be integers, not unicode

Expected O/P is

{u'red: u'ele-ven', u'blue': u'twe.lve'} 

OR a json string will also do like

{"red": "ele-ven", "blue": "twe.lve"}

Upvotes: 2

Views: 633

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599866

dict2 is apparently not a dict at all, but a string; presumably JSON. You probably need to parse it first: dict2 = json.loads(dict2).

Upvotes: 2

Related Questions