[英]Printing from a dictionary in Python
{
"intents": [
{
"name": "goodbye",
"created": "2017-08-18T18:09:36.155Z",
"updated": "2017-08-18T18:09:41.755Z",
"description": null
},
{
"name": "hello",
"created": "2017-08-18T18:05:48.153Z",
"updated": "2017-08-18T18:06:06.004Z",
"description": null
}
],
"pagination": {
"refresh_url": "/v1/workspaces/9978a49e-ea89-4493-b33d-82298d3db20d/intents?version=2017-08-21"
}
}
這一切都保存在一個名為 response 的變量中,該變量包含超過 200 個值的字典。
如果我只打印“響應”,它會打印以上所有內容,包括“創建/更新/描述”。 我只想打印出名稱值……但我不知道該怎么做。
我在這里閱讀了一些帖子並嘗試了以下操作 -
for value in response:
print(value['intent'])
但同樣,這會打印出所有內容(包括描述/更新日期等)。
我怎樣才能讓它只打印出名字?
作為獎勵,我如何將名稱列表添加到我可以迭代的數組中?
看樣子你要訪問的name
每個子字典的屬性在intents
。 這應該有效 -
for d in response['intents']:
print(d['name'])
如果您希望將其存儲在列表中,請使用列表理解:
names = [d['name'] for d in response['intents']]
將名稱添加到列表中並打印:
names = [intent["name"] for intent in response["intents"]]
print(*names, sep='\n')
看看我的解決方案
names_list = []
for x in response["intents"]:
print x["name"] # it will print all of your names
names_list.append(x["name"]) # it will add the names into the names_list
print names_list
希望它會幫助你:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.