-2

I have a list (named Responses) which contains some dictionary with the following key-value pair:

Responses = [
    {'Id':100,'ResponseText1':'aaaa','ResponseText2':'yyyy'},
    {'Id':101,'ResponseText1':'bbbb','ResponseText2': 'zzzz'},
    {'Id':103,'ResponseText1':'cccc'},
    {'Id':104,'ResponseText2': True},
]

As you can see here Id is a common field for all dictionary, but ResponseText1 and ResponseText2 are unavailable for some dictionary.

I want to separate and detect all the data to push them into my database. My python code:

for j in Responses:
    print(j['Id'])
    if j['ResponseText1']:
        print(j['ResponseText1'])
    else:
        print("No ResponseText1 is present")
    if j['ResponseText2']:
        print(j['ResponseText2'])
    else:
         print("No ResponseText2 is present")

But It says errors like:

Traceback (most recent call last):
File "<string>", line 14, in <module>
KeyError: 'ResponseText2'

Please suggest how can I fix this?

Kanchon Gharami
  • 777
  • 1
  • 11
  • 30
  • 2
    Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – Pranav Hosangadi Oct 05 '21 at 18:11

1 Answers1

1

Use in or .get('key', default), not ['key'] access to prevent KeyErrors

example of both

for j in Responses:
    print(j['Id'])
    text1 = j.get('ResponseText1')
    if text1 is not None:
        print(text1)
    else:
        print("No ResponseText1 is present")

    if 'ResponseText2' in j:
        print(j['ResponseText2'])
    else:
         print("No ResponseText2 is present")
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245