Create Dict within list of dict

十年热恋 提交于 2021-02-05 09:41:38

问题


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 = {
    'site': '', 
    'listofiles': [
        {'time': '', 'name': ''}
    ]
}

exampledata = {
    'site': 'DC1', 
    'listofiles': [
        {'time': 'Thu Oct 3 22:26:40 2019', 'name': 'file1'}, 
        {'time': 'Thu Oct 3 20:26:40 2019', 'name': 'file2'}, 
        {'time': 'Thu Oct 3 21:26:40 2019', 'name': 'file3'}
    ]
} 

How to populate data within the var? I have tried doing the following, but it will only give me
{ 'DC1': [file1,file2,file3], 'DC2': [file1,file2] }

exampledata = {}
for f in os.listdir(path):
   exampledata.setdefault(f.split('.')[1],[]).append(f)

回答1:


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



回答2:


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})


来源:https://stackoverflow.com/questions/58291996/create-dict-within-list-of-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!