嵌套-字典中的列表和来自同一索引的值

时间:2019-05-19 03:29:08

标签: python python-3.x dictionary nested nested-lists

我有一个字典,其中包含约470个键/值对,其中值是嵌套列表。看起来像这样:

{'sample1': [0.052333365, 0.048546686, 0.037446034, 0.034170007, 0.027255262, 0.014583427, 0.022703695, 0.02747237, 0.036779904, 0.047089636, 0.068311633, 0.131601903, 0.213325007, 0.262173714], 
'sample2': [0.499261188, 0.569225594, 0.971341941, 0.983553048, 1.047320154, 1.214003077, 1.382066271, 1.332965957, 1.353788699, 1.224310364, 1.27942017, 1.297752738, 1.215054777, 1.336544035], 
'sample3': [3.015670427, 3.608257648, 3.060244617, 2.879527679, 2.720453311, 2.889312783, 2.899236274, 2.762219639, 3.257009779, 3.113135178, 3.312874684, 3.328944661, 3.564360549, 3.480976541]}

它最初是这样创建的,这是由于访问数据的客户端基于行(样本)的关注。每个指标都是相隔2个月进行的测量。

最近,这种情况本质上已变得更加柱状,并且我正在获得有关可以在特定的2个月内跨所有样本学习的问题。

我的问题是,是否有一种简单的方法可以为所有样本提取索引[1]或[5]中的值,并且仍然能够识别值来自哪个样本,而不必将数据重新创建为二维清单?

3 个答案:

答案 0 :(得分:1)

您可以使用字典items()和索引值:

for k, v in d.items():
    print(f'{k} -> {v[1]}, {v[5]}')

其中d是您的字典。

对于给定的输入,将输出:

sample1 -> 0.048546685999999999, 0.014583426999999999
sample2 -> 0.56922559399999995, 1.2140030770000001
sample3 -> 3.6082576479999999, 2.8893127829999998

答案 1 :(得分:1)

  

是否有一种简便的方法可以提取所有样本的索引[1]或[5]中的值,并且仍然能够识别值来自哪个样本,而不必将数据重新创建到二维列表中?

您可以使用字典理解

假设您的示例字典存储在名为data的变量中,我们要提取第6位的值

row_5 = {k: v[5] for k, v in data.items()} 
# row_5 prints
{'sample1': 0.014583427, 'sample2': 1.214003077, 'sample3': 2.889312783}

您可以构建一个函数以通用的方式执行此操作。

def get_row(row_num, data_dict):
    return {k: v[row_num] for k, v in data_dict.items()}

如果您想要更多的数据处理功能,建议您进入pandas库。

答案 2 :(得分:0)

We can use a dictionary comprehension to recreate a dictionary with only the data from specified indexes.

def get_data(dct, indexes):

    #Iterate through value list and collect element from specified indexes
    return {key: [value[idx] for idx in indexes] for key, value in dct.items()}

So for indexes [1,5], the output will be

print(get_data(dct, [1,5]))
#{'sample1': [0.048546686, 0.014583427], 'sample2': [0.569225594, 1.214003077], 'sample3': [3.608257648, 2.889312783]}