字符串索引必须是整数,而不是字符串 - 从字典中检索值 [英] String indices must be integers, not string - retrieving value from dictionary

查看:1652
本文介绍了字符串索引必须是整数,而不是字符串 - 从字典中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字典中检索一个值。它在我的代码的一部分工作正常,但随后在下一个中断。

 如果用户不是无:

用户[用户名] =临时 - +用户[用户名]

打印USER ID:+ str(user [ID])#Works fine
#来源帐户中的用户
patch_user(用户,头文件)

补丁用户:


$ b $ pre $ def patch_user(user,headers):
根据用户的ID $ b修补用户字段$ b
patched_user = request('patch_user',user [AccountID],user,headers)

然后请求:

  def请求(request,account_id,user,headers):
向服务器发送用户请求
向服务器发送请求

url = api_root +/ accounts /+ str(account_id)

function_dictionary = {'get_user_from_id':(requests.get,#Function
(url +/ users /+ str(user),),#参数参数
{'headers':headers}),#Dictionary of keyword args

'patch_user' (request.patch,
(url +/ users /+ str(user [ID])),
{'headers':headers,'data':json.dumps )})

func,args,kwargs = function_dictionary [request]
result = func(* args,** kwargs)

# 200响应
result.raise_for_status()

#查询结果
打印查询+请求+结果:+ result.text

返回结果

我收到以下错误:

  TypeError:string indices必须是整数,而不是str 

(url +/ users /+ str(user [ID]),),



任何帮助不胜感激!



修改
完整跟踪:


 追溯(最近的最后一次呼叫):
文件C:\Program文件(x86)\Microsoft Visual Studio 12.0 \Common7\IDE\Extensio
ns\Microsoft\Python Visual Studio的工具\2.0\visualstudio_py_util.py,第7行
6,在exec_file
exec( code_obj,global_variables)
文件C:\Front-End\pcli-front
.py,第179行,< module>
user_operations.move_user(arguments ['< source>'],arguments ['< destination>'],
arguments ['< id>'],标题)
文件 C:\Front-End\user_opera
ctions.py,第27行,在move_user
user = get_user_from_id(source_account,user_id,headers)
文件C:\Front- $ _ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\
文件C:\Front-End\\ \\ user_opera
ctions.py,第131行,请求
(url +/ users /+ str(user [ID]),),
TypeError:作为整数,而不是str


解决方案

完全不同于你认为的代码路径。 patch_user 与它无关;堆栈跟踪显示问题来自 get_user_from_id



它看起来像请求意味着从 patch_user get_user_from_id 中调用不同的内容。当 patch_user 调用它时, user 是一个dict。当 get_user_from_id 调用它时, user 是表示用户ID的字符串。问题是,请求仍然尝试构建完整的 function_dictionary ,而不管其所做的请求是哪种类型,所以这行:

 (url +/ users /+ str(user [ID]),),

即使用户是一个字符串,仍然运行。要解决这个问题,您可以使用else / if链而不是字典,以避免在不运行时运行有问题的代码,也可以将请求分成单独的每种请求类型的方法。


I am trying to retrieve a value from a dictionary. It works fine in one part of my code but then breaks in the next.

if user is not None:

    user["Username"] = "Temp-"+user["Username"]

    print "USER ID: " + str(user["ID"]) #Works fine
    #Rename user in source account
    patch_user(user, headers)

Patch User:

def patch_user( user, headers ):
    """Patch a User field based on their ID
    """
    patched_user = request('patch_user', user["AccountID"], user, headers)

Then in request:

def request( request, account_id, user, headers):
    """Send a User request to the server
    Send a request to the server
    """
    url = api_root + "/accounts/" + str(account_id)

    function_dictionary = {'get_user_from_id': (requests.get,                       #Function
                                               (url + "/users/" + str(user),),      #Tuple of Arguments
                                               {'headers': headers}),               #Dictionary of keyword args

                               'patch_user':(requests.patch,
                                             (url + "/users/" + str(user["ID"]),),
                                             {'headers': headers, 'data':json.dumps(user)})

    func, args, kwargs = function_dictionary[request]
    result = func(*args, **kwargs)

    #Throw exception if non-200 response
    result.raise_for_status()

    #Result from query
    print "Query " + request + " result: " + result.text

    return result

I get the following error:

TypeError: string indices must be integers, not str

at (url + "/users/" + str(user["ID"]),),

Any help is appreciated!

Edit Full Trace:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensio
ns\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py", line 7
6, in exec_file
    exec(code_obj, global_variables)
  File "C:\Front-End\pcli-front
.py", line 179, in <module>
    user_operations.move_user(arguments['<source>'],arguments['<destination>'],
arguments['<id>'], headers)
  File "C:\Front-End\user_opera
tions.py", line 27, in move_user
    user = get_user_from_id(source_account, user_id, headers)
  File "C:\Front-End\user_opera
tions.py", line 68, in get_user_from_id
    user = request('get_user_from_id', account_id, user_id, headers)
  File "C:\Front-End\user_opera
tions.py", line 131, in request
    (url + "/users/" + str(user["ID"]),),
TypeError: string indices must be integers, not str

解决方案

Your exception is coming from an entirely different code path than you think it is. patch_user has nothing to do with it; the stack trace shows that the problem is coming from get_user_from_id.

It looks like the third argument of request means something different when called from patch_user or get_user_from_id. When patch_user calls it, user is a dict. When get_user_from_id calls it, user is a string representing a user ID. The problem is that request still tries to build the full function_dictionary regardless of which type of request it's making, so this line:

(url + "/users/" + str(user["ID"]),),

still runs even when user is a string. To fix this, you could use an else/if chain instead of the dictionary to avoid running the problematic code when it shouldn't be run, or you could divide request into separate methods for each request type.

这篇关于字符串索引必须是整数,而不是字符串 - 从字典中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆