![](/img/trans.png)
[英]How to pop out a key-value pair from within a another key value pair in dictionaries in python
[英]Is there a way to create a string out of a key-value pair from a dictionary in python?
例如,我有一本字典:
{"John": "Doe", "Jane" : "Smith", "Jack" : "Poland"}
我想創建一個列表
["John Doe", "Jane Smith", "Jack Poland"]
給定 dict names
,您可以在列表推導中使用 f 字符串。
[f'{key} {value}' for key, value in names.items()]
列表理解中的 f 字符串將是最有效的,看起來有人已經回答過了。
另一種可能更容易理解的方法是只做一個for
循環並遍歷字典一次。 使用一些 python 字符串連接,您可能已經學會了,然后將 append 放到一個新列表中。 (僅供參考:f-string 方法具有相同的結果,但代碼更少)
使用字符串連接:
full_name = []
name_dict = {"John": "Doe", "Jane" : "Smith", "Jack" : "Poland"}
for first, last in name_dict.items():
name = first + " " + last
full_name.append(name)
print(full_name)
還有其他一些方法,但是這個方法和 f 弦馬上就出現在我身上。
您還可以在頂部定義多個變量和列表,這比將所有內容放在一行上更容易混淆,並且與您可能完成的其他練習類似,而且更有條理。
另一個巧妙的事情是,您在 for 循環中的單獨變量中擁有名稱; 在你 append 之前,它還沒有出現在你的新列表中。 這很酷,因為如果您想對組合字符串執行任何其他操作,而不僅僅是 append 列表,您也可以使用該變量。
試試這個:
dic = {"John": "Doe", "Jane" : "Smith", "Jack" : "Poland"}
lst =[key+" "+value for key,value in dic.items()]
print(lst)
output:
['Jack Poland', 'John Doe', 'Jane Smith']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.