'I am not able to get dictionary keys

**I made an api request in which the content iconverted into dictionary but after nested key item all the other content were in string which I wanted to in dictionary to make it easy to find mint address so as it was in string I seperated that part and replaced all braces and the converted into dictionary using loop as traditional method of ast and json were not giving desired result but the end dictionary is showing an error when I am using .key() comannd that there is no key **

import requests
import convReq # this is private module i'll provide its code down below
import json
import ast
def user_details(nft_address):
    xurl='https://api.solscan.io/transfer/token?token_address='+nft_address+'&type=all&offset=0&limit=1'
    #return byte array
    datar=requests.get(xurl).content
    xy=convReq.convert_to_dict(datar)
    return xy

y=(user_details("EwESGGqNuPLdK4Q5yLAiTEtDJm15FrPFT3ZyoCRcDgpd"))
print(type(y))
x=json.dumps(y['data']['items'])
print(x)
print ("\n", type(x))

#print ("final string = ", x)

x=x.replace("[","").replace("]","").replace("{","").replace("}","").replace('"',"")
word=""
dict={}
wkey=""
for char in x:
    if char==":":
        wkey=word
        word=""
    elif char==",":
        dict[wkey]=word
        word=""
    else:
        word=word+char

print("--------------------------------------------------------------------------------------------")
print(dict)
print(type(dict))
print(dict["mint"])


################################
#private code convReq part
import ast
from ast import literal_eval
import json
def convert_to_dict(xdata):
     xdata=str(xdata, 'UTF-8')
     xdata=json.loads(xdata)
     return(xdata)

def convert_to_json(my_byte):
    my_json=my_byte.decode('utf8').replace("'",'"')
    datax=json.loads(my_json)
    s=json.dumps(datax,indent=4,sort_keys=True)
    return s


Solution 1:[1]

You code is correct, but you are not considering the whitespaces in the string, that is causing you problems.

Instead of mint as key, the dictionary was storing mint as key. that's where key not found comes into picture.

Adding the below replace(' ', "") fixes the problem.

x = x.replace("[", "").replace("]", "").replace(
    "{", "").replace("}", "").replace('"', "").replace(' ', "")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhinava B N