![](/img/trans.png)
[英]What's a Pythonic way to add a list (or other iterator) of key/value pairs to a dict?
[英]Pythonic way to transform list of pairs to dict
我有這樣一個配對列表:
[
{'Name': 'first_name', 'Value': 'Joe'},
{'Name': 'last_name', 'Value': 'Smith'},
{'Name': 'gender', 'Value': 'male'}
]
我想將其轉換成這樣的Dict:
{
'first_name': 'Joe',
'last_name': 'Smith',
'gender': 'male'
}
我目前正在使用一個簡單的循環來完成此操作,但我知道還有一種更Python化的方法可以執行此操作。 有什么想法嗎?
-托尼
這比我預期的容易:
{pair['Name']:pair['Value'] for pair in source_list}
這使用了稱為Dict理解的Python功能。
您可以在列表中的每個字典上使用values()
方法的生成器輸出實例化字典:
dict(d.values() for d in l)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.