如何创建包含元组和列表的值的字典

时间:2017-05-10 02:09:02

标签: python-3.x dictionary tuples

我试图定义一个函数来创建一个这样的字典:

d = {}
d['aod'] = [('nt', 'P3', ['af1', 'af2', 'af3']),
            ('t', 'P3', ['af1', 'af2', 'af3']),
            ('nv', 'P3', ['af1', 'af2', 'af3'])]    

我能够让字典看起来像这样:

d = {'aod': ('nt', 'P3')}

使用以下代码:

experiment = ['aod']
cond_peaks = ['nt_P3', 't_P3', 'nv_P3']
channel_lst = ['af1', 'af2', 'af3']

def create_dict(experiment, cond_peaks, channel_lst):
    d = {}
    for e in experiment:
        for cp in cond_peaks: 
            cond = cp.split('_')[0]
            peak = cp.split('_')[1]
            cond_peak_tup = cond, peak
            d[e] = cond_peak_tup
    return d

由于元组是不可变的,我无法将channel_lst添加到字典值。我的问题是如何创建一个字典,其中值包含元组和列表?

2 个答案:

答案 0 :(得分:1)

你可以这样定义你的元组:

cond_peak_tup = cond, peak, channel_lst

并使用临时列表

d = {}
for e in experiment:
    l = []
    for cp in cond_peaks: 
        cond = cp.split('_')[0]
        peak = cp.split('_')[1]
        cond_peak_tup = cond, peak, channel_lst
        l.append(cond_peak_tup)
    d[e] = l
return d

更优雅的是,您还可以使用字典和列表推导一致创建所有内容(假设使用Python 3.5或更新版(*cp.split('_'), channel_lst)语法):

d = {e: [(*cp.split('_'), channel_lst) for cp in cond_peaks]
     for e in experiment}

对于旧版本,您必须执行以下操作:

d = {e: [tuple(cp.split('_') + [channel_lst]) for cp in cond_peaks]
     for e in experiment}

在我看来,后者解决方案不仅速度更快,而且对于具有Python语言能力的读者来说也更具可读性,而前者对学习或调试非常有用。但这当然是一种风格问题。

答案 1 :(得分:0)

你可以在dict comprehension中的一行中使用此输入执行此操作:

experiment = ['aod']
cond_peaks = ['nt_P3', 't_P3', 'nv_P3']
channel_lst = ['af1', 'af2', 'af3']

final = {k:[(j.split("_")[0],j.split("_")[1],channel_lst,) for j in cond_peaks] for k in experiment}


print(final)

输出:

{'aod': [('nt', 'P3', ['af1', 'af2', 'af3']), ('t', 'P3', ['af1', 'af2', 'af3']), ('nv', 'P3', ['af1', 'af2', 'af3'])]}