我在Python中有以下字典。我想访问第二个值,并将其分配给新的var new时间。我试图使用列表来完成此操作,但是我无法找到所需的答案
exampledict = {
"a": ["url1", "file_name1"],
"b": ["url2", "filename2"],
"d": ["url4", "filename4"],
"c": ["url3", "filename3"],}
for key, value in exampledict.items():
url = value[0]
filename = value[1]
# do stuff with url and filename
# later:
# I want to do something will all my filenames without getting them again from the dict.
所以实际结果是每次存储文件名是4个diff变量,以便我可以访问它。我试图使用一个空列表然后扩展,但是这样做使我得到了四个单独的列表格式文件,而不是一个包含所有4个文件的列表(以便我可以使用索引访问)。逐步的帮助以及我犯了什么逻辑错误
请忽略代码中的任何语法错误
答案 0 :(得分:1)
无需扩展,只需迭代地填充列表即可:
exampledict = {
"a": ["url1", "file_name1"],
"b": ["url2", "filename2"],
"d": ["url4", "filename4"],
"c": ["url3", "filename3"],}
filenames = []
for key, value in exampledict.items():
url = value[0]
filename = value[1]
# do more stuff
print ("In loop", url, filename)
filenames.append(filename)
print(filenames)
输出:
In loop url1 file_name1
In loop url2 filename2
In loop url4 filename4
In loop url3 filename3
['file_name1', 'filename2', 'filename4', 'filename3']
如果您只对文件名感兴趣,可以直接提取它们:
fns = [filename for _,filename in exampledict.values()]
答案 1 :(得分:0)
您错过了词典中“ d”行中的昏迷,
尝试一下:
urls = []
files = []
exampledict = {
"a": ["url1", "file_name1"],
"b": ["url2", "filename2"],
"d": ["url4", "filename4"],
"c": ["url3", "filename3"],}
for key, value in exampledict.items():
url = value[0]
urls.append(url)
filename = value[1]
files.append(filename)
现在您访问数组网址和文件中的信息,例如:
print(urls[0])... print(urls[3])
print(files[0])...print(files[3])