【问题标题】:Can't return a dictionary from my function [closed]无法从我的函数返回字典[关闭]
【发布时间】:2014-08-12 04:31:55
【问题描述】:

我收到一个无效的语法错误

 SyntaxError: invalid syntax
 root@collabnet:/home/projects/twitterBot# python twitterBot2.py
 File "twitterBot2.py", line 58
 return screenNames

当从此函数返回字典时:

def getUserName(lookupIds):
     l = len(lookupIds) # length of list to process
     i = 0 #setting up increment for while loop 
     screenNames = {}#output dictionary
     count = 0 #count of total numbers processed
     print 'fetching usernames'
     while i < l:
         toGet = []
         toAppend = []
         if l - count > 100:#blocks off in chunks of 100
             for m  in range (0,100):
                toGet.append(lookupIds[count])
                count = count + 1
                print toGet
         else:#handles the remainder 
             print 'last run'
             r = l - count 
             print screenNames
             for k  in range (0,r):#takes the remainder of the numbers 
                 toGet.append(lookupIds[count])
                 count = count + 1
             i = l   # kills loop

         toAppend = api.lookup_users(user_ids=toGet)
         print toAppend
         screenNames.append(zip(toGet, toAppend)

         #creates a dictionary screenNames{user_Ids, screen_Names}

     #This logic structure breaks up the list of numbers in chunks of 100 or their
     #Remainder and addes them into a dictionary with their count number as the 
     #index value   
     #print str(len(toGet)), 'screen names correlated'
     return screenNames

我正在运行这样的功能:

 toPrint = {}#Testing Only
 print "users following", userid 
 toPrint = getUserName(followingids)#Testing Only

我尝试注释掉并打印screenNames,但我仍然得到相同的错误,除了打印语句。我很确定我正在运行退货,感谢您的外观。

【问题讨论】:

  • 您提供的缩进是否与您的代码中的一样?
  • 另外,screenNames 被定义为一个 set/dict(它是模棱两可的,因为你使用了一个空的 {} 初始化器),但是你用 append 向它添加元素,这不是对dictset 均有效。
  • @aruisdante:这绝对是一个字典,没有歧义。您不能以这种方式定义空集。该行的评论甚至清楚地表明了 OP 期望在该行上发生什么。
  • @MartijnPieters 哦,你是对的,我忘记了 Python 不允许空集文字正是为了解决所说的歧义;)

标签: python dictionary return


【解决方案1】:

您忘记了前一行的右括号:

screenNames.append(zip(toGet, toAppend)
#                 ^   ^               ^^?
#                 |   \---- closed ---/|
#                 \----- not closed ---/

这里还有一个问题,因为screenNames 是一个dict 对象,而不是一个列表,并且没有.append() 方法。如果您想使用键值对更新字典,请改用update()

screenNames.update(zip(toGet, toAppend))

【讨论】:

  • 尽管AttributeError 无论如何都会失败,因为screenNamesset/dict,因此没有append
猜你喜欢
  • 1970-01-01
  • 2019-04-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 2019-11-22
  • 2011-05-01
  • 1970-01-01
相关资源
最近更新 更多