字典的名單我有兩個Python列表如下所示:轉換列表在Python
fruits = ["apple", "banana", "guava", "grapes"]
colour = ["red", "yellow", "green", "black"]
我想將它們轉換成以下格式的詞典:
dictionary = [{"fruit":"apple", "colour":"red"},{"fruit":"banana", "colour":"yellow"}...]
字典的名單我有兩個Python列表如下所示:轉換列表在Python
fruits = ["apple", "banana", "guava", "grapes"]
colour = ["red", "yellow", "green", "black"]
我想將它們轉換成以下格式的詞典:
dictionary = [{"fruit":"apple", "colour":"red"},{"fruit":"banana", "colour":"yellow"}...]
郵編你的水果和顏色列表一起使用zip()
function,並從每對創建一個新詞典:
[{'fruit': f, 'colour': c} for f, c in zip(fruits, colour)]
這使用list comprehension來創建循環的列表輸出。
演示:
>>> fruits = ["apple", "banana", "guava", "grapes"]
>>> colour = ["red", "yellow", "green", "black"]
>>> [{'fruit': f, 'colour': c} for f, c in zip(fruits, colour)]
[{'colour': 'red', 'fruit': 'apple'}, {'colour': 'yellow', 'fruit': 'banana'}, {'colour': 'green', 'fruit': 'guava'}, {'colour': 'black', 'fruit': 'grapes'}]
一如既往,您的好回答!但請記住,即使是Python初學者也可能不理解在列表理解中壓縮列表或循環的幾個變量賦值... – linusg
@linusg:我在這裏接受後續評論,通常有SO問題和文檔可以指向。 –
一個很好的解決方案,我發現是使用一個外部的CSV文件來管理您的字典 例如dict.csv爲csv文件
import csv
import os
dictionary = os.getcwd() + r'\dict.csv'
with open(dictionary, mode='r') as infile:
reader = csv.reader(infile)
mydict = {rows[0]:rows[1] for rows in reader}
的直供並且在csv文件中可以具有第一列作爲第二列的顏色。易於修改和管理
考慮提供更多的細節,如你已經嘗試過的代碼等:) – Kannaj
非常相似:http://stackoverflow.com/questions/4576115/convert-a-list-to-a -python中的詞典?rq = 1 –