【发布时间】:2016-05-21 01:24:00
【问题描述】:
我正在 python 中创建一个嵌套字典,其中包含存储在 Amazon S3 存储桶中的文件的条目。因此,如果在我的存储桶中,我有几个这样的文件:
mys3bucket/subdir/world.txt
mys3bucket/subdir/hello.txt
mys3bucket/foobar.txt
我想用python制作一个这种格式的字典:
dict = { 'subdir' : { 'world.txt' : 'file', 'hello.txt' : 'file' }, 'foobar.txt' :'file' }
值('file')在这种情况下没有意义,但它们可以替换为文件的大小或其他东西(对于这个问题,这无关紧要)。关键是字典必须嵌套,因为子目录,显然嵌套的级别取决于特定树的深度。我已经编写了一个已经这样做的工作实现:
#!/usr/bin/python
import httplib
from re import compile as recomp
pattern = recomp("<Key>(.*?)<\/Key>")
def main(bucketname='elasticmapreduce'):
url = bucketname + '.s3.amazonaws.com'
HTTPconnection = httplib.HTTPConnection(url)
HTTPconnection.request("GET", "/")
response = HTTPconnection.getresponse()
content = response.read()
fileslist = pattern.findall(content)
filesdict = {}
def intoDict(path,mydict):
if len(path) == 1:
mydict[path[0]] = 'file'
return mydict
else:
name = path.pop(0)
if name in mydict:
mydict[name] = intoDict(path,mydict[name])
else:
mydict[name] = intoDict(path,{})
return mydict
for line in fileslist:
splitline = line.split('/')
if splitline[-1] != '':
filesdict = intoDict(splitline,filesdict)
return filesdict
默认存储桶名称只是设置为我发现能够测试代码的公共存储桶。
使用正则表达式的原因是,当您查询存储桶时,S3 会返回一个 XML 格式的文本,因此正则表达式只是从中提取文件路径。
我很好奇我的实施效率。正如您在 for 循环中看到的那样,我每次都将整个字典传递给 intoDict() 函数,并在它返回时重新编写它。 intoDict() 函数是递归/自引用的,这就是嵌套的产生方式。解释发生了什么有点困难,但我想你可以看到。我花了一段时间才找到这个解决方案,因为起初我试图使用dictionary.update() 来更新for 循环内的字典,但它不能正常工作。
我想知道是否有经验丰富的嵌套字典和/或递归函数的人可以评论这是否是实现我正在尝试的正确方法,或者是否可以做得更好。
【问题讨论】:
标签: python dictionary recursion amazon-s3 hashmap