简体   繁体   English

python如何在列表中的字典中创建字典

[英]python how to create dictionaries in dictionaries from lists

I have a list of file names, experiments = ['f1','f2','f3','f4'], times of day, t = ['am','pm'], and types of data collected, ['temp','humidity']. 我有文件名列表,实验= ['f1','f2','f3','f4'],一天中的时间,t = ['am','pm']和收集的数据类型, ['temp','湿度']。

From these I want to create dictionaries within dictionaries in the following format: 从这些,我想以以下格式在词典中创建词典:

dict = {'f1': { am : {'temp': [], 'humidity': []} , pm : {'temp': [], 'humidity': []}},
        'f2': { am : {'temp': [], 'humidity': []} , pm : {'temp': [], 'humidity': []}},
        'f3': { am : {'temp': [], 'humidity': []} , pm : {'temp': [], 'humidity': []}},
        'f4': { am : {'temp': [], 'humidity': []} , pm : {'temp': [], 'humidity': []}}}

What's the best way to do this? 最好的方法是什么? Many thanks in advanced. 非常感谢高级。

{z: {y: {x: [] for x in data_types} for y in t} for z in experiments}

A case for comprehensions if I ever saw. 我曾经见过一个理解的案例。

from copy import deepcopy
datatypes = ['temp','humidity']
times = ['am','pm']
experiments = ['f1','f2','f3','f4']

datatypes_dict = dict((k, []) for k in datatypes)
times_dict = dict((k, deepcopy(datatypes_dict)) for k in times)
experiments_dict = dict((k, deepcopy(times_dict)) for k in experiments)

or the nicer dict comprehension way (python 2.7+) 或更好的dict理解方式(python 2.7+)

datatypes_dict = {k: [] for k in datatypes}
times_dict = {k: deepcopy(datatypes_dict) for k in times}
experiments_dict = {k: deepcopy(times_dict) for k in experiments}

you can nest them but it gets mind-blowing pretty quick if things are at all complicated. 您可以嵌套它们,但是如果事情很复杂的话,它很快就会令人惊讶。

In this use case, however, @marshall.ward's answer 但是,在此用例中,@ marshall.ward的答案

{z: {y: {x: [] for x in data_types} for y in t} for z in experiments}

is far better than mine, as you can avoid the deepcopy()ing. 比我的要好得多,因为您可以避免使用deepcopy()。

Taking some artistic license with the output format 使用输出格式获取一些艺术许可

>>> from collections import namedtuple, defaultdict
>>> from itertools import product
>>> experiments = ['f1','f2','f3','f4']
>>> times_of_day = ['am','pm']
>>> data_types = ['temp','humidity']
>>> DataItem = namedtuple('DataItem', data_types)
>>> D=defaultdict(dict)
>>> for ex, tod in product(experiments, times_of_day):
...     D[ex][tod]=DataItem([], [])
... 
>>> D
defaultdict(<type 'dict'>, {'f1': {'am': DataItem(temp=[], humidity=[]), 'pm': DataItem(temp=[], humidity=[])}, 'f2': {'am': DataItem(temp=[], humidity=[]), 'pm': DataItem(temp=[], humidity=[])}, 'f3': {'am': DataItem(temp=[], humidity=[]), 'pm': DataItem(temp=[], humidity=[])}, 'f4': {'am': DataItem(temp=[], humidity=[]), 'pm': DataItem(temp=[], humidity=[])}})

You can access the data items like this 您可以像这样访问数据项

>>> D['f1']['am'].temp
[]
>>> D['f1']['am'].humidity
[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM