在字典列表中创建字典 [英] Create Dict within list of dict

查看:133
本文介绍了在字典列表中创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在字典列表中创建一个字典.我该如何建立数据结构,然后再通过jinja2来获取数据?这是一个示例:

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'}
    ]
} 

如何在var中填充数据?我已尝试执行以下操作,但这只会给我
{'DC1':[file1,file2,file3],'DC2':[file1,file2]}

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)

推荐答案

注意!不要在代码中将路径"名称用于变量或其他任何东西,就像python的builin模块的名称一样.

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

使用以下代码.make_var函数带有2个变量,第一个变量是站点的名称,第二个变量是目录的路径,其中包含您需要为其注册的所有文件.代码仅适用于Python3

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

这篇关于在字典列表中创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆