我想在字串中使用字典串列中的資料。例如
dict = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}]
print(f"His name is {??} and he is {??} years old")
我需要知道用什么替換問號才能使其正常作業。
我看了很多堆疊溢位并發現了一些東西,但沒有得到一個特定的專案。我發現
print([item["name"]for item in dict])
uj5u.com熱心網友回復:
dict = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}]
dict是字典串列。(順便說一下,糟糕的變數名選擇。 dict已經是 Python 內置的東西的名稱,所以通過使用它作為變數名,你已經失去了它的原始含義。另外,你正在使用dict來保存一個串列人,所以這個名字本身意義不大。 people會是一個更好的名字。)
串列通過整數索引訪問。因此,在本例中,dict[0]是 Matt 的條目,dict[1]也是 Sally 的條目。
現在您知道dict[0]是 Matt 的條目,您可以使用標準的字典鍵語法。
Matt 的名字是dict[0]['name'],他的年齡是dict[0]['age']。
同樣,Sally 的名字是dict[1]['name'],她的年齡是dict[1]['age']。
(所有這些都是非常基本的 Python 語法。您到底在哪一部分遇到了問題?)
uj5u.com熱心網友回復:
遍歷字典,然后使用[]運算子獲取name和age鍵。
people = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}]
for p in people:
print(f"Their name is {p['name']} and they are {p['age']} years old")
Their name is Matt and they are 21 years old
Their name is Sally and they are 28 years old
uj5u.com熱心網友回復:
- 用于列印所有人員
dict:
for person in dict:
print(f"His name is {person['name']} and he is {person['age']} years old")
輸出:
His name is Matt and he is 21 years old
His name is Sally and he is 28 years old
- 要在 中列印一個人
dict,請使用他的索引(1本例中為索引):
print(f"His name is {dict[1]['name']} and he is {dict[1]['age']} years old")
輸出:
His name is Sally and he is 28 years old
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534504.html
標籤:Python列表字典
