digdigdoot
digdigdoot

Reputation: 761

How to create a list of dictionaries using for loop?

Textfile:

VIP Room,      10,   250
Executive Room,30,   500
Pool Site,     50,   850
Banquet Hall,  200,  1000
Chamber Hall,  500,  2000
Concert Hall,  1000, 3500

My code so far to read the file and create a list:

def readVenueList():
    dic={}
    venueList=[]
    f=open("venue.txt","r")
    for line in f:
        line = line.split(",")
        print(line)
        for i in line:
            i.split()
            dic["name"]=i[0]
            dic["num"]=i[1]
            dic["cost"]=i[2]
            venueList.append(dic)
    return(venueList)

How do I create a list of dictionaries with the following output?

venueList = [{'cost': '250', 'name': 'VIP Room', 'num': '10'},
             {'cost': '250', 'name': 'Executive Room', 'num': '30'},
                # and so on and so forth...
            ]

Upvotes: 1

Views: 3250

Answers (4)

martineau
martineau

Reputation: 123443

Here's how to modify your code do it properly (and follow the PEP 8 - Style Guide for Python Code recommendations more closely) :

from pprint import pprint

def readVenueList():
    venueList = []

    with open("venue.txt", "r") as f:
        for line in f:
            dic = {}
            items = [item.strip() for item in line.split(",")]
            dic["name"] = items[0]
            dic["num"] = items[1]
            dic["cost"] = items[2]
            venueList.append(dic)

    return venueList

venueList = readVenueList()
pprint(venueList)

Output:

[{'cost': '250', 'name': 'VIP Room', 'num': '10'},
 {'cost': '500', 'name': 'Executive Room', 'num': '30'},
 {'cost': '850', 'name': 'Pool Site', 'num': '50'},
 {'cost': '1000', 'name': 'Banquet Hall', 'num': '200'},
 {'cost': '2000', 'name': 'Chamber Hall', 'num': '500'},
 {'cost': '3500', 'name': 'Concert Hall', 'num': '1000'}]

Upvotes: 0

Edward Minnix
Edward Minnix

Reputation: 2937

If you don't want to use a CSV reader (though that's probably the best idea), you could also do this using list/dictionary comprehensions

with open('venue.txt', 'r') as f:
    lines = (line.split(',') for line in f)
    venues = [
        {'name': name.strip(), 'number': int(num), 'cost': int(cost)}
        for name, num, cost in lines
    ]

Upvotes: 0

N M
N M

Reputation: 616

You can simply use the csv reader library to handle this.

import csv
headers = ['name', 'num', 'cost']
with open('venue.txt', 'r') as f:
    reader = csv.reader(f)
    needed_list = [{headers[i]: row[i].strip() for i in range(3)} for row in reader]

Upvotes: 2

Supreet Sethi
Supreet Sethi

Reputation: 1806

It is very similar to earlier answer by @N M

datablob = u"""VIP Room,10,250
Executive Room,30,500
Pool Site,50,850
Banquet Hall,200,1000
Chamber Hall,500,2000
Concert Hall,1000,3500
"""
from csv import reader
from io import StringIO

def readVenueList(fd):
    c = reader(fd)
    hdr = ["name", "num", "cost"]
    for i in c:
        d = {}
        for el, v in enumerate(i):
            d[hdr[el]] = v
        yield d

if __name__ == '__main__':
    # replace with file object
    # file = open("archive1.csv")
    file = StringIO(datablob)
    print(list(readVenueList(file)))
    # Output
    [{'name': 'VIP Room', 'num': '10', 'cost': '250'}, {'name': 
     'Executive Room', 'num': '30', 'cost': '500'}, {'name': 'Pool 
      Site', 'num': '50', 'cost': '850'}, {'name': 'Banquet Hall', 
     'num': '200', 'cost': '1000'}, {'name': 'Chamber Hall', 'num': 
     '500', 'cost': '2000'}, {'name': 'Concert Hall', 'num': '1000', 
     'cost': '3500'}]

Upvotes: 0

Related Questions