Create Dict within list of dict

前端 未结 2 1823
挽巷
挽巷 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
    
    0 讨论(0)
  • 2021-01-28 12:12

    Not sure what do you mean by 'site' ...

    The code below uses site as location on the file system. It iterates over the sites list and read the files for each site.

    import os
    import datetime
    
    data = dict()
    
    sites = ['.']
    for site in sites:
        data['listofiles'] = []
        data['site'] = site
        for f in os.listdir(site):
            data['listofiles'].append(
                {'time': str(datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(site, f)))), 'name': f})
    
    0 讨论(0)
提交回复
热议问题