[英]Create Dict within list of dict
我正在嘗試在字典列表中創建一個字典。 如何構建數據結構,然后通過 jinja2 獲取數據? 這是一個例子:
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'}
]
}
如何在var中填充數據? 我嘗試過以下操作,但它只會給我{ 'DC1': [file1,file2,file3], 'DC2': [file1,file2] }
exampledata = {}
for f in os.listdir(path):
exampledata.setdefault(f.split('.')[1],[]).append(f)
筆記! 不要在代碼中使用“路徑”名稱作為變量或任何東西,就像 python 的內置模塊的名稱一樣
使用以下代碼。 make_var function 有兩個變量,第一個變量是站點名稱,第二個變量是目錄路徑,其中包含您需要注冊的所有文件。 代碼僅適用於 Python3
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
不知道你所說的“網站”是什么意思...
下面的代碼使用站點作為文件系統上的位置。 它遍歷站點列表並讀取每個站點的文件。
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})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.