简体   繁体   English

如何使用 python 中的索引从 json 列表中获取值?

[英]How do I get a value from a json list using an index in python?

How can I print 'abcd' here?我怎样才能在这里打印'abcd'?


import json

my_dict = {
    "test": "hello world",
    'my_list': [{
        'a_value': "abcd",
        'another_value': 'asdf'
    }]
}

stuff = json.dumps(my_dict)
stuff = json.loads(stuff)

e = stuff[my_list][1] # An attempt
print(e) # IndexError: list index out of range

I want to specifically use the index (1, not 'a_value').我想专门使用索引(1,而不是'a_value')。

Try this:-尝试这个:-

import json

my_dict = {
    "test": "hello world",
    'my_list': [{
        'a_value': "abcd",
        'another_value': 'asdf'
    }]
}

stuff = json.dumps(my_dict)
stuff = json.loads(stuff)

e = my_dict['my_list'][0]['a_value']
print(e) 

It will work!它会起作用的!

There are 2 problems with your attempt:您的尝试有两个问题:

  1. my_list is a key in the json object, it works similar to a dict. my_list 是 json object 中的一个键,它的作用类似于 dict。 Therefore, you must refer to it as a key in the object and enclose it in ''.因此,您必须在 object 中将其称为键并将其括在 '' 中。
  2. 'my_list' has the value of a list, therefore the first element of the list shall be accessed, and only then can you access the key 'a_value'. 'my_list' 具有列表的值,因此应访问列表的第一个元素,然后才能访问键 'a_value'。

In dictionary or json objects, you cannot refer to the keys via an index.在字典或 json 对象中,您不能通过索引引用键。 Therefore, you cannnot use '1' to refer to 'a_value'.因此,您不能使用“1”来引用“a_value”。 Your other option could be to create a list of the values of the object and then use the index.您的其他选择可能是创建 object 的值列表,然后使用索引。 This can be done as:这可以这样做:

import json

my_dict = {
    "test": "hello world",
    'my_list': [{
        'a_value': "abcd",
        'another_value': 'asdf'
    }]
}

stuff = json.dumps(my_dict)
stuff = json.loads(stuff)
e = list(list(stuff.values())[1][0].values())[0]
print(e)

The output of the above statement will be:上述语句的 output 将是:

abcd

Or, as suggested by @Dr.或者,正如@Dr. 所建议的那样。 Strange Codes, you could do something like this although I am guessing this is not what you are looking for:奇怪的代码,你可以做这样的事情,虽然我猜这不是你想要的:

e = stuff['my_list'][0]['a_value']

The output will be: output 将是:

abcd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM