简体   繁体   中英

Add item to a list in a dict

I have a program that works as intended:

import os
import hashlib
from pprint import pprint


def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()


lst = []
for dirpath, dirnames, filenames in os.walk('d:\\python\\exercism.io'):
    d = {dirpath: filenames}
    for filename in filenames:
        d[filename] = [os.stat(dirpath).st_mtime, md5(dirpath + '\\' + filename)]
        # d[filename] = [os.stat(dirpath).st_mtime]
        # d[filename] = [md5(dirpath + '\\' + filename)]
    lst.append(d)

pprint(lst)

My question is this:

If I get rid of this line:

        d[filename] = [os.stat(dirpath).st_mtime, md5(dirpath + '\\' + filename)]

and try to use the two commented out lines (with a modification -- see below) it fails.

1) Either commented out line works by themselves. I get a key: value pair in which the value is a list.

I then want to add the value of the second commented out line to the list.

I was trying this:

        d[filename][1] = md5(dirpath + '\\' + filename)

but I get an index out of range error. The first element of the list should be item [0], the second should be [1].

Partial output:

[{'ceasar_cipher.py': [1512494094.5630972, '844e069c90ebdb3e1e5f5dd56da2ac2e'],
  'd:\\python\\exercism.io': ['ceasar_cipher.py',
                              'difference_of_squares.py',
                              'gigasecond.py',
                              'grains_in_python.py',
                              'hamming-compare.py',
                              'isogram.py',
                              'leap_year.py',
                              'rna_transcription.py',
                              'run_length_encoding.py'],

Note the key: 'ceasar_cipher.py' has a value which is a two element list.

I want to construct the exact same output with the two commented out lines versus the single line I am using now (just so I can, not that I should). My concern is simply what am I doing wrong.

You need to append to your list:

d[filename] = [os.stat(dirpath).st_mtime]
d[filename].append(md5(dirpath + '\\' + filename))

to get the same effect. There is no item at index 1 yet. You need to create it, for example with append() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM