访问字典中的列表

时间:2020-11-06 08:56:44

标签: python list api loops dictionary

WHERE 
DATEADD(YEAR,-1, GETDATE()) -- One Day Before Today in the Last Year
AND 
DATEADD(yy, DATEDIFF(yy, 0, DATEADD(YEAR,-1, GETDATE())), 0) AS StartOfYear -- The Day 1 of the Last Year

我想访问此词典中人员列表中的名称。 请帮我解决一下这个。 谢谢

3 个答案:

答案 0 :(得分:0)

您将不得不为此字典添加一个名称

dict1 = {'message': 'success', 
  'people': [
        {'name': 'Sergey Ryzhikov', 'craft': 'ISS'},
        {'name': 'Kate Rubins', 'craft': 'ISS'},
        {'name': 'Sergey Kud-Sverchkov', 'craft': 'ISS'}

   ], 
   'number': 3}
# And then this will access it, by looping over the list and printing out all of the 3 names
for i in dict['people']:
    print(i['name'])

答案 1 :(得分:0)

这是一段非常简单的代码。

d = {'message': 'success', 'people': [{'name': 'Sergey Ryzhikov', 'craft': 'ISS'}, {'name': 'Kate Rubins', 'craft': 'ISS'}, {'name': 'Sergey Kud-Sverchkov', 'craft': 'ISS'}], 'number': 3}


for data in d.get("people"):
    print(data.get("name"))

我建议您使用.get()方法而不是方括号来访问字典中的值,以避免出现异常。

答案 2 :(得分:-1)

遍历人员列表并选择要获取的dict属性

data = {'message': 'success',
        'people': [{'name': 'Sergey Ryzhikov', 'craft': 'ISS'}, {'name': 'Kate Rubins', 'craft': 'ISS'},
                   {'name': 'Sergey Kud-Sverchkov', 'craft': 'ISS'}], 'number': 3}

for p in data['people']:
    print(p['name'])

输出

Sergey Ryzhikov
Kate Rubins
Sergey Kud-Sverchkov