bigd
bigd

Reputation: 69

Making a dictionary of images

I know I asked this before, but I'm still not sure why I only get the date in the list now instead of the location, date, and caption in the list when I test this. Can anyone please help me fix this? The end result is supposed to look like this.

{filename: [location, date, caption]}

I got this

{'images/skating.jpg': {'East York Arena': ['2014.11.03']}, 
'images/sunglasses.jpg': {'High Park': ['2013.02.03']}, 
'images/skating2.jpg': {'East York Arena': ['2014.11.03']}}

Here is the file.

images/skating.jpg,East York Arena,2014.11.03,Shea skating.,skating,Shea,boy
images/sunglasses.jpg,High Park,2013.02.03,Cool guy.,Shea,sunglasses,happy
images/skating2.jpg,East York Arena,2014.11.03,Shea skating 
again!,skating,Shea

def create_image_dict(open_csv_file):
'''(file) -> dict of {str: list of str}

The open csv file has the format:
filename,location,date,caption,keywords,keywords, ...
Return a dictionary with key filename and values [location, date, caption]
'''
d = {}
for line in open_csv_file:
    info = line.split(',')
    filename = info[0]
    location = info[1]
    date = info[2]
    caption = info[3]
    if location not in d:
        d[filename] = {location:{date: caption}}
return d

Upvotes: 2

Views: 1714

Answers (2)

Adam Smith
Adam Smith

Reputation: 54213

Scharette's answer appropriately points out the core error here, that {filename: {location: {date: caption}}} is a dict of dict of dicts, rather than your requested dict of lists ({filename: [location, date, caption]}), but I wanted to comment briefly about your code in general.

First of all, you're using a comma-separated format in your file, so use the stdlib module specifically designed to handle those files -- csv.

import csv

with open("filename.csv") as f:
    reader = csv.reader(f)

Reader objects are iterables of iterables, representing lines -> fields. This makes it easy to do:

    # from above
    for line in reader:
        fname, location, date, caption = line[:4]

the slice [:4] here doesn't grab the first four characters of line, it operates over the first four comma-separated fields, so your last sample line becomes

fname = 'images/skating2.jpg'
location = 'East York Arena'
date = '2014.11.03'
caption = 'Shea skating again!'

You can actually wrap this all in a dictionary comprehension, too.

with open("filename.csv") as f:
    reader = csv.reader(f)
    result = {fname: (location, date, caption) for line in reader
              for fname, location, date, caption in line[:4]}

Upvotes: 0

scharette
scharette

Reputation: 9977

Well this is exactly what you told Python to do here:

  d[filename] = {location:{date: caption}}

so replace it by this:

d[filename] = [location,date,caption]

Upvotes: 2

Related Questions