开发者

Attempting to create something using dictionaries but am lost

I'm not really too sure how to best approach the following in python... I know what I want, and have an idea of how I want it, but I don't know if my idea is the best approach to what I'm looking for.

"Name":"path",contains[]
"Folder":"C:/blah/blah/folder",contains["file1","file2","file3"]

like

things={}
things["Folder"]="C:/blah/blah/folder" AND开发者_开发百科 contains["file1","file2","file3"]

so that it can be used like:

for folder,path,contents in things.iteritems():  
    print("%s @ \"%s\" containing:\n\t")%(folder,path)  
    for file in contents:  
        print("%s\n\t")%(file)  

and how could I add things to contents, something like

content.append(blah)

Any help would be appreciated! Thanks.


Something like this?

>>> d = {}
>>> d["Folder"] = ["C:/blah/blah/Folder", ["file1","file2","file3"]]
>>> d["more"] = ["/home/mydir", ["file1","file2","file3"]]
>>> d["Folder"][0]
'C:/blah/blah/Folder'
>>> d["Folder"][1]
['file1', 'file2', 'file3']
>>> d["Folder"][1].append("file4")
>>> d["Folder"][1]
['file1', 'file2', 'file3', 'file4']
>>> for entry in d:
...     d[entry][1].append("newfile")
...
>>> d
{'Folder': ['C:/blah/blah/Folder', ['file1', 'file2', 'file3', 'file4', 'newfile']],
 'more': ['/home/mydir', ['file1', 'file2', 'file3', 'newfile']]}


I think you're looking for a nested dictionary:

things = {"Folder" : {"path" : "C:/blah/folder", "contents" : ["file1", "file2"]},
          "Directory" : {"path" :"C:/foo/dir", "contents" : ["fileX", "fileY"]}}
for folder, info in things.iteritems():
  print("%s @\"%s\" containing:\n\t")%(folder, info["path"])
  for file in info["contents"]:
    print("%s\n\t")%(file)


things = {}
things["Folder"] = ("C:/blah/blah/folder", ["file1","file2","file3"])

for folder, (path, contents) in things.iteritems():
    print("%s @ \"%s\" containing:\n\t")%(folder,path)  
    for file in contents:  
        print("%s\n\t")%(file)  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜