1

I have two python lists like the following:

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

I wish to convert them into a dictionary of the following format:

dictionary = [{"fruit":"apple", "colour":"red"},{"fruit":"banana", "colour":"yellow"}...]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
glitterati
  • 133
  • 2
  • 16

2 Answers2

10

Zip your fruit and colour lists together using the zip() function, and build a new dictionary from each pair:

[{'fruit': f, 'colour': c} for f, c in zip(fruits, colour)]

This uses a list comprehension to create the list output from a loop.

Demo:

>>> 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'}]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • As always a good answer of you! But keep in mind that even Python beginners might not understand zipping of lists or for loops with several variable assignments in a list comprehension... – linusg May 13 '16 at 12:47
  • 2
    @linusg: I'm here for follow-up comments, there usually are SO questions and documentation we can point to. – Martijn Pieters May 13 '16 at 12:48
0

A good solution I found is to use an external CSV file to manage your dictionary for example the dict.csv is the directry of the csv file

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}

and in the csv file can have first column as fruits second column as color. Easy to modify and manage

cheng chen
  • 479
  • 1
  • 4
  • 6