Create Dict within list of dict

前端 未结 2 1850
挽巷
挽巷 2021-01-28 11:26

I\'m trying to create a dict within a list of dicts. How do I build the data structure and later to fetch the data via jinja2? Here is an example:

var = {
    \         


        
2条回答
  •  死守一世寂寞
    2021-01-28 12:04

    note! don't use 'path' name in your code for variable or anything as is the name of a builin module of python

    use the following code. make_var function take 2 variables, the first variable is the site's name and the second variable is the directory's path which contains all the files you need to register for it. code is for Python3 only

    from datetime import datetime as dt
    from pathlib import Path
    
    
    def make_var(site_name, pth): 
        exampledata = {'site':site_name, 'listofiles':[]}
        p = Path(pth)
        for f in p.iterdir():
            if f.is_file():
                name = f.name.replace(f.suffix, '')
                tm = dt.utcnow().strftime('%a %b %H:%M:%S %Y')
                exampledata['listofiles'].append({'time':tm, 'name':name}) 
        return exampledata
    

提交回复
热议问题