Python:将数据从字典中拉出,就像2D数组一样

时间:2014-08-08 02:47:47

标签: python numpy dictionary

我有一个python字典,其中所有值都是相同长度的数组。我希望能够通过元素编号提取这些值。

我有这样的字典:

dictionary = { 'key1': [1,2,3], 'key2': [4,5,6], 'key3': [7,8,9] }

在调用参数1时我想要这个输出:

[2,5,8]

我所拥有的最好的是

[dictionary.values()[0][1], dictionary.values()[1][1], dictionary.values()[2][1] ]

因为

dictioinary.values()[:][1]
即使dictionary.values()返回一个列表,

也不起作用。

或者将这些数据存储在2D数组中还是使用numpy更容易?我想使用字典,所以我可以通过密钥调用数据。

4 个答案:

答案 0 :(得分:4)

使用纯Python,您可以使用列表解析:

In [106]: [dictionary[key][1] for key in ('key1', 'key2', 'key3')]
Out[106]: [2, 5, 8]

(因为dict键是无序的,如果你想按顺序访问对应于'key1','key2','key3'的值,你必须明确说明键,或者使用像sorted(dictionary.keys()))。


爬上方便的阶梯,你可以改为使用NumPy。以下将字典转换为数组:

In [111]: arr = np.array([dictionary[key] for key in ('key1', 'key2', 'key3')]).T

In [112]: arr
Out[112]: 
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

选择数组的第二行:

In [113]: arr[1]
Out[113]: array([2, 5, 8])

并选择第二列:

In [120]: arr[:, 1]
Out[120]: array([4, 5, 6])

如果要按键名称引用列,则可以定义键映射:

In [126]: keymap = dict(zip(('key1', 'key2', 'key3'), range(3)))

In [127]: keymap
Out[127]: {'key1': 0, 'key2': 1, 'key3': 2}

In [128]: arr[:, keymap['key2']]
Out[128]: array([4, 5, 6])

即使在更方便的阶梯上,也有Pandas: Pandas DataFrames支持基于列和/或索引(行)标签访问数据:

In [129]: import pandas as pd

In [130]: df = pd.DataFrame(dictionary)

In [131]: df
Out[131]: 
   key1  key2  key3
0     1     4     7
1     2     5     8
2     3     6     9

In [132]: df['key2']
Out[132]: 
0    4
1    5
2    6
Name: key2, dtype: int64

In [133]: df.iloc[1]  # Get the second row of the DataFrame
Out[133]: 
key1    2
key2    5
key3    8
Name: 1, dtype: int64

答案 1 :(得分:1)

p = lambda index: [val[index] for val in dictionary.values()]
p(0) #will give 0th index of the array

答案 2 :(得分:0)

如果您熟悉Matlab并且需要对行和列进行操作,那么numpy是一个不错的选择

>>> import numpy as np
>>> matrix = np.matrix('1,2,3;4,5,6;7,8,9')
>>> matrix[:,2]
matrix([[3],
        [6],
        [9]])
>>> matrix[:,1]
matrix([[2],
        [5],
        [8]])

但是你可以创建一个2D数组并实现自己的函数来提取列

m = [[1,2,3],
     [4,5,6],
     [7,8,9]]

def column(matrix, i):
    return [row[i] for row in matrix]

在您的终端

>>> column(m, 1)
[2, 5, 8]

或直接使用理解

[row[1] for row in m]

答案 3 :(得分:0)

您可以使用map和itemgetter。

check here地图做什么

from operator import itemgetter dictionary = { 'key1': [1,2,3], 'key2': [4,5,6], 'key3': [7,8,9] } map(itemgetter(1), dictionary.values())

然而,由于值会迭代字典,因此会返回无序列表。

您可以尝试对结果进行反向操作。我不确定使用OrderedDict表单集合包是否也是个好主意

我没有看到使用numpy来解决这个问题。我错过了什么吗?