[英]How to get a particular key value in a list of dictionaries using python
您好,這是我的第一個 stackoverflow 問題,請耐心等待。
我的 JSON 文件如下所示:
{"users":
[
{"name": "John Smith",
"phone_num":"+104484932"
},
{"name": "Linda Ray",
"phone_num": "+194387282"
}
]
}
當給出輸入時,腳本應該在這個字典列表中查找名稱並返回電話號碼,我嘗試了很多資源,它看起來也可能是這個問題的副本。
不是,感謝您提前提供幫助。
將 json 文件加載到 python 字典中,然后遍歷users
列表。
def myfunction(target_name):
with open('file.json') as f:
data = json.load(f)
for user in data['users']:
if user['name'] == target_name:
return user['phone_num']
你可以用一種簡單的方式來做
json = {"users":
[
{"name": "John Smith",
"phone_num":"+104484932"
},
{"name": "Linda Ray",
"phone_num": "+194387282"
}
]
}
inp = input('Name: ')
print([i['phone_num'] for i in json['users'] if i['name'] == inp][0])
告訴我它是否不起作用...
我們無權訪問您的代碼,因此不確定您采用的是哪種方法。 假設這是簡單的准系統。
如果文件是 json,則需要讀入它,這將要求我們導入json
庫。
import json
這個問題意味着我們直接從用戶那里獲得輸入,所以我們可以使用input()
函數來收集這些數據。 在這里,我們提供了一個提示,該提示將在腳本運行時顯示在屏幕上。
username = input("Please supply a name: ")
從那里,我們讀入json
文件,該文件作為 Python 字典讀入。 由於它是一個字典(Python dict()
),我們可以深入研究它以獲取我們關心的數據,查詢特定keys
以查看相關values
。
當我們open()
文件時,我選擇將打開的文件稱為fin
。 然后我們提取存儲在users
鍵下的內容(該值恰好是一個人的list
)。
with open('filename.json') as fin:
book = json.load(fin)
users = data['users']
然后我們解析用戶列表中的每個用戶並檢查是否與之前輸入的username
匹配。 當它找到匹配項時,它會打印相應的電話號碼。
for user in users:
if user['name'] == username:
print(user['phone_num'])
整個腳本看起來像這樣:
import json
username = input("Please supply a name: ")
with open('filename.json') as fin:
book = json.load(fin)
users = data['users']
for user in users:
if user['name'] == username:
print(user['phone_num'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.