[英]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. 1)要么自己注释掉线路工作。 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].
列表的第一个元素应为项目[0],第二个元素应为[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. 请注意密钥:'ceasar_cipher.py'具有一个包含两个元素的列表。
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.
索引1尚无项目。 You need to create it, for example with
append()
. 您需要创建它,例如,使用
append()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.