Regarding Keyerror while using Python json module
<p>would be helped if the mistake is pointed. 
Here Iam trying to create a code for displaying the name of the city state and country by taking Pincode as input, Thanks in advance</p>

<pre><code>    import urllib, json
from urllib.request import urlopen
from tkinter import *
global pincode
root=Tk()
frame=Frame(root,width=250,height=250)
frame.grid()
class cal:

    def __init__(self):
        self.string=StringVar()
        entry=Entry(frame,textvariable=self.string)
        entry.grid(row=1,column=2,columnspan=6)
        but=Button(root,text="submit",command=self.pin)
        but.grid()
    def pin(self):
        pincode=self.string.get()

        url = "https://www.whizapi.com/api/v2/util/ui/in/indian-city-by-postal-code?pin="+pincode+"&amp;project-app-key=fnb1agfepp41y49jz6a39upx"
        response = urllib.request.urlopen(url)
        data = json.loads(response.read().decode('utf8'))
        fi=open("neme.txt","w")
        fi.write(str(data))        
        state=data['State']
        city=data['City']
        area=data['area']
        name=Label(frame,text="State:"+state+"City:"+city+"area:"+area)
        name.grid(row=3,column=0)







    cal()

    mainloop()
</code></pre>

<p>error being </p>

<pre><code>Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__
    return self.func(*args)
  File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Pn_code.py", line  24, in pin
    state=data['State']
KeyError: 'State'
</code></pre>

<p>Ok. Error tells you that you don't have key named "State" in you dict under <code>data</code> variable. So maybe there isn't also in incomming json.</p>

<p>If in response you get:</p>

<pre><code>{"ResponseCode":0,"ResponseMessage":"OK","ResponseDateTime":ââ"9/3/2016 2:41:25 PM GMT","Data":[{"Pincode":"560103","Address":"nagar","City":"Bââanalore","State":"naââtaka","Country":"Indââia"}]}
</code></pre>

<p>then you cannot get "State" by using:</p>

<pre><code>data["State"]
</code></pre>

<p>you have to do it using:</p>

<pre><code>data["Data"][0]["State"]
</code></pre>

<p>and the rest:</p>

<pre><code>data["Data"][0]["City"]
data["Data"][0]["Country"]
</code></pre>

<p>Why in this way? Because you have to get nested keys, first key is <code>"Data"</code>, using <code>data["Data"]</code> you recieve a list, and because it's one element list, you have to get first item of the list: <code>data["Data"][0]</code>. And at the end under <code>data["Data"][0]</code> you get dict of keys where you can find State, City, Country.</p>

python json python-3.x