我在一个变量结果中有多个字典.如何从中只返回第一个字典值



我在一个变量结果中有多个字典。如何从中只返回第一个字典值

for result in results:
print(result)

输出为:

{'Title': 'John'}
{'Title': 'Mark'}
{'Title': 'Adam'}
{'Title': 'Ethen'}
{'Title': 'Tom'}

我想返回第一个字典'john'的值

使用dict的键访问值

print(results[0]['Title'])

如果你有一个字典列表或元组,你可以使用索引:

results[0]

其中0对应于列表中的第一个字典,因为Python中的索引从0开始。

最好更改字典的键。或者您可以使用var[0]或使用var〔title〕

您可能希望将输出格式化为dicts的列表,以便输出为

result = [
{'Title': 'John'},
{'Title': 'Mark'},
{'Title': 'Adam'},
{'Title': 'Ethen'},
{'Title': 'Tom'}
]

然后可以清楚地看到,通过索引result[0]['Title']可以获得'John'

dict.values((可以用于

results=({'Title': 'John'},{'Title': 'Mark'},{'Title': 'Adam'},{'Title': 'Ethen'},{'Title': 'Tom'})
d=results[0]    #to store first dictionary
print(d.values())  #to get value of first dictionary
print(results[0]["title"])

如果你只想要第一个项目的值,你不需要使用循环

最新更新