将列表转换为python中的词典列表

时间:2016-05-13 12:39:20

标签: python python-2.7

我有两个python列表,如下所示:

fruits = ["apple", "banana", "guava", "grapes"]  
colour = ["red", "yellow", "green", "black"]  

我希望将它们转换为以下格式的字典:

dictionary = [{"fruit":"apple", "colour":"red"},{"fruit":"banana", "colour":"yellow"}...]

2 个答案:

答案 0 :(得分:10)

使用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'}]

答案 1 :(得分:0)

我发现一个很好的解决方案是使用外部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文件中可以将第一列作为水果第二列作为颜色。易于修改和管理