Python, KeyError – Stack Overflow em Português

Olá, estou aprendendo a linguagem python agora, e preciso urgente programar um bot para o Instagram de um cliente! quanto executo o código, me vem essa mensagem, com esse problema logo abaixo.

Traceback (most recent call last):
  File "vamos.py", line 10, in <module>
    session.like_by_tags(('shirts'), amount=5)
  File "C:UserslidioAppDataLocalProgramsPythonPython36libsite-packagesinstapyinstapy.py", line 1967, in like_by_tags
    self.logger,
  File "C:UserslidioAppDataLocalProgramsPythonPython36libsite-packagesinstapylike_util.py", line 637, in check_link
    media = post_page(0)("shortcode_media")
KeyError: 0

peço que me ajudem! pois estou batendo a cabeça para resolver esse problema. Obrigado e até.

python – How to fix Keyerror in GBTclassifier confusion matrix

while working with gbt classifier received an error in convolution matrix as keyerror…

cm_gbt_result = predictions_gbt.crosstab("prediction", "indexedLabel")
cm_gbt_result = cm_gbt_result.toPandas()
cm_gbt_result
#calculate accuracy, sensitivity, specificity and precision
TP = cm_gbt_result("1")(0)
FP = cm_gbt_result("0")(0)
TN = cm_gbt_result("0")(1)
FN = cm_gbt_result("1")(1)
Accuracy = (TP+TN)/(TP+FP+TN+FN)
Sensitivity = TP/(TP+FN)
Specificity = TN/(TN+FP)
Precision = TP/(TP+FP)

print ("Accuracy = %0.2f" %Accuracy )
print ("Sensitivity = %0.2f" %Sensitivity )
print ("Specificity = %0.2f" %Specificity )
print ("Precision = %0.2f" %Precision )

Trace of above mentioned code:

Traceback

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2894             try:
-> 2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '1'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
2 frames
<ipython-input-56-24962cb86bab> in <module>()
      1 #calculate accuracy, sensitivity, specificity and precision
----> 2 TP = cm_gbt_result("1")(0)
      3 FP = cm_gbt_result("0")(0)
      4 TN = cm_gbt_result("0")(1)
      5 FN = cm_gbt_result("1")(1)

/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in __getitem__(self, key)
   2904             if self.columns.nlevels > 1:
   2905                 return self._getitem_multilevel(key)
-> 2906             indexer = self.columns.get_loc(key)
   2907             if is_integer(indexer):
   2908                 indexer = (indexer)

/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:
-> 2897                 raise KeyError(key) from err
   2898 
   2899         if tolerance is not None:

KeyError: '1'

can anyone suggest me why this error occured and how to resolve it…since i’m new to python ..if any silly errors please forgive me

python – KeyError: & # 39; id & # 39; after 100 key-value pairs have already been printed

I use Python to print the results of a view in CouchDB that contains key-value pairs of the result of a reduction function.
Everything works via the graphical interface of the browser, but with Python every 100 elements printed in the console gives me the following errors:

Traceback (most recent call last):

  File "D:UsersDesktopEsercitazioni NoSQLEsercitazione4MaxCasesView.py", line 31, in 
    for r in result:

  File "D:UsersDesktopEsercitazioni NoSQLEsercitazione4cloudantresult.py", line 400, in _iterator
    if last('id'):

KeyError: 'id'

This is the code:

result = db.get_view_result(ddoc, view_name, group = True)
for r in result:
    print(r('key'), "tt : ", r('value'))

When i do result = db.get_view_result(ddoc, view_name, group = True, skip = 100) it prints another 100 results and the 200th result gives me the same errors.

Is it possible to solve this problem or do I need to find a way to reload the view for every 100 items printed?

I'm using Python 3.8 and Cloudant libraries for CouchDB 3.1

Python – KeyError does not understand:

I'm trying to create an interactive dictionary. The file data.json contains the definition of the words. I expected the code to look up the definition of a user-entered word and dump it to the terminal.

Import Json

data = json.load (open ("data.json", & # 39; r)))
item = input ("Enter the word you are looking for:")
dates["%s", item]
print (data) 

However, I get the following error message

Enter the word you are looking for: Rain
Traceback (last call last):
File "C:  Users  Hassan  eclipse-workspace  FTS  src  FirstModule.py", line 10, in 
    dates["%s", item]
KeyError: (& # 39;% s & # 39 ;, & # 39; rain & # 39;)

I do not understand what causes the error or how I can fix it. Can someone please point out where I make the mistake and suggest a possible solution.

thank you in advance

api – Python – Json: KeyError

I'm putting the call into a MailChimp API, where I paste the fields into my database.
The JSON provided in the documentation displays the following fields:

{
"Automation": [
  {
    "id": "b0a1c24f1a",
    "create_time": "2015-09-15T14:31:54+00:00",
    "start_time": "2015-09-15T15:45:32+00:00",
    "status": "paused",
    "emails_sent": 1,
    "recipients": {
      "list_id": "57afe96172"
    },
    "settings": {
      "title": "Freddie's Best Jokes",
      "from_name": "Freddie",
      "reply_to": "freddie@freddiesjokes.com",
      "use_conversation": false,
      "to_name": "*|FNAME|*",
      "authenticate": true,
      "auto_footer": false,
      "inline_css": false
    },
    "tracking": {
      "opens": true,
      "html_clicks": true,
      "text_clicks": true,
      "goal_tracking": true,
      "ecomm360": true,
      "google_analytics": "Freddie_s_Best_Jokes9_15_2015",
      "clicktale": ""
    },
    "trigger_settings": {
      "workflow_type": "emailSeries",
      "send_immediately": false,
      "trigger_on_import": false,
      "runtime": {
        "days": [
          "sunday",
          "monday",
          "tuesday",
          "wednesday",
          "thursday",
          "friday",
          "saturday"
        ],
"Hours": {
"send_at": "12:00 am"
}
},
"workflow_emails_count": 1
},
"report_summary": {
"opens": 1,
"unique_opens": 1,
"open_rate": 1,
"Clicks": 0,
"subscriber_clicks": 0,
"click_rate": 0
},
"_Left": [
      {
        "rel": "parent",
        "href": "https://usX.api.mailchimp.com/3.0/automations",
        "method": "GET",
        "targetSchema": "https://api.mailchimp.com/schema/3.0/Automations/Collection.json",
        "schema": "https://api.mailchimp.com/schema/3.0/CollectionLinks/Automations.json"
      },
      {
        "rel": "self",
        "href": "https://usX.api.mailchimp.com/3.0/automations/b0a1c24f1a",
        "method": "GET",
        "targetSchema": "https://api.mailchimp.com/schema/3.0/Automations/Instance.json"
      },
      {
        "rel": "start-all-emails",
        "href": "https://usX.api.mailchimp.com/3.0/automations/b0a1c24f1a/actions/start-all-emails",
        "method": "POST"
      },
      {
        "rel": "pause-all-emails",
        "href": "https://usX.api.mailchimp.com/3.0/automations/b0a1c24f1a/actions/pause-all-emails",
        "method": "POST"
      },
      {
        "rel": "emails",
        "href": "https://usX.api.mailchimp.com/3.0/automations/b0a1c24f1a/emails",
        "method": "GET",
        "targetSchema": "https://api.mailchimp.com/schema/3.0/Automations/Emails/Collection.json"
      },
      {
        "rel": "removed-subscribers",
        "href": "https://usX.api.mailchimp.com/3.0/automations/b0a1c24f1a/removed-subscribers",
        "method": "GET",
        "targetSchema": "https://api.mailchimp.com/schema/3.0/Automations/RemovedSubscribers/Collection.json"
      }
    ]
  }
],
"total_items": 1,
"_Left": [
  {
    "rel": "parent",
    "href": "https://usX.api.mailchimp.com/3.0/",
    "method": "GET",
    "targetSchema": "https://api.mailchimp.com/schema/3.0/Root.json"
  },
  {
    "rel": "self",
    "href": "https://usX.api.mailchimp.com/3.0/automations",
    "method": "GET",
    "targetSchema": "https://api.mailchimp.com/schema/3.0/Automations/Collection.json",
    "schema": "https://api.mailchimp.com/schema/3.0/CollectionLinks/Automations.json"
  }
]
  }

Here is the code I call:

From Mailchimp3 Import MailChimp
Import psycopg2

client = MailChimp (& # 39; e22ce5ad29a0422f19b66b7d697faf7e-us17 & # 39; mauricio.bezerra & # 39;)
r = client.automations.all (get_all = True)


conn = psycopg2.connect ("dbname =" db "user =" user "= host" # 39 ")
Password = & # 39; Password & # 39; ")
INSERT INTO table (status, list_is_active, title, emails_sent, unique_opens, subscriber_clicks, open_rate, click_rate) VALUES "

info = r

record =[]
for info in info['automations']:
record.append (((
Info['status'],
Info['recipients']['list_is_active'],
Info['settings']['title'],
Info['emails_sent'],
Info['report_summary']['unique_opens'],
Info['report_summary']['subscriber_clicks'],
Info['report_summary']['open_rate'],
Info['report_summary']['click_rate']

                

                

                

                ))

if len> 0:
cur = conn.cursor ()
join (cur.mogrify ("(% s,% s,% s,% s,% s,% s,% s)", x) for x in the record)
Command = Insert + y.decode ()
Try:
cur.execute ("Table TRUNCATE TABLE")
cur.execute (command)
conn.commit ()
Exception (exception, psycopg2.DatabaseError) as error:
print (error)

cur.close ()
print (& # 39; Full Load & # 39;)
otherwise:
conn.close ()
print (& # 39; nothing to paste & # 39;)

When I run it, the following error is thrown:

Exception occurred: KeyError
& # 39; # 39 & report_summary;

Should I call this field in a different way?

"report_summary": {
"opens": 1,
"unique_opens": 1,
"open_rate": 1,
"Clicks": 0,
"subscriber_clicks": 0,
"click_rate": 0
}