相关疑难解决方法(0)

在Python3中按索引访问dict_keys元素

我正在尝试通过索引访问dict_key的元素:

test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys()  # dict_keys object

keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'
Run Code Online (Sandbox Code Playgroud)

我想得到foo.

同样的:

keys[0]
TypeError: 'dict_keys' object does not support indexing
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

python dictionary key python-3.x

107
推荐指数
4
解决办法
10万
查看次数

返回Dictionary中的第一个键 - Python 3

我正在尝试使用以下代码打印密钥和值:

data = {"Key1" : "Value1", "Key2" : "Value2"}
print(data.keys()[1])   
print(data.values()[1])
Run Code Online (Sandbox Code Playgroud)

我收到了错误

'dict_keys' object does not support indexing
Run Code Online (Sandbox Code Playgroud)

提到的代码有什么问题?

接受的输出:

Key2
Value2
Run Code Online (Sandbox Code Playgroud)

python python-3.x

8
推荐指数
3
解决办法
2万
查看次数

如何修复“TypeError”-“dict_keys”对象不可下标?

我对 Python 完全陌生,我只是在练习和“复制”一些 github 代码。在这样做的过程中,我意识到我正在使用最新版本的Python,而视频中的人正在使用Python 2.7,因此他使用的代码与我的不兼容。请帮助我如何重写代码。

def add_friend(self,friend_id):
    check_req = requests.get('https://gift-f06e4.firebaseio.com/.json?orderBy="my_friend_id"&equalTo=' + friend_id)

    data = check_req.json()
    print(check_req.ok)
    print(check_req.json())
    if data == {}:
        self.root.ids['add_friend_screen'].ids['add_friend_label'].text = "Invalid friend ID"

    else:
        key = data.keys()[0]
        new_friend_id = data[key]['my_friend_id']
        print('New friend id is', new_friend_id)
Run Code Online (Sandbox Code Playgroud)

问题出现在这一行:

key = data.keys()[0]
Run Code Online (Sandbox Code Playgroud)

我知道这不是我在 Python 3 中编写这部分的方式,但我不知道如何让它工作。

python typeerror

5
推荐指数
2
解决办法
2万
查看次数

标签 统计

python ×3

python-3.x ×2

dictionary ×1

key ×1

typeerror ×1