2017-05-29 91 views
0

我有以下的解釋:篩選器列表的字典在Python

dict = {'Sex':['Male','Male','Female','Female','Male'], 
     'Height': [100,200,150,80,90], 
     'Weight': [20,60,40,30,30]} 

我希望能夠過濾使用條件字典上的一個鍵。例如,如果我想繼續只限男性:

new_dict = {'Sex':['Male','Male','Male'], 
      'Height': [100,200,90], 
      'Weight': [20,60,30]} 
+1

將其轉換成數據庫。 –

+1

謝謝但我的配置不理想。 – user2475110

+0

你想成爲多麼靈活?可以舉另一個例子爲「height> 100」嗎? –

回答

4

您可以使用字典理解和相應的指數,在檢查項目在關鍵'Sex'在構建值列表:

d = {k: [x for i, x in enumerate(v) if dct['Sex'][i]=='Male'] 
             for k, v in dct.items()} 
print(d) 
# {'Sex': ['Male', 'Male', 'Male'], 
# 'Weight': [20, 60, 30], 
# 'Height': [100, 200, 90]} 
3

,而不是試圖跟蹤指數的,「轉」的數據結構是一個字典列表:

data = [{'Sex': 'Male', 'Height': 100, 'Weight': 20}, 
     {'Sex': 'Male', 'Height': 200, 'Weight': 60}, 
     {'Sex': 'Female', 'Height': 150, 'Weight': 40}, 
     {'Sex': 'Female', 'Height': 80, 'Weight': 30}, 
     {'Sex': 'Male', 'Height': 90, 'Weight': 30}] 

only_males = [person for person in data if person['Sex'] == 'Male'] 
only_males 
# [{'Sex': 'Male', 'Height': 100, 'Weight': 20}, 
# {'Sex': 'Male', 'Height': 200, 'Weight': 60}, 
# {'Sex': 'Male', 'Height': 90, 'Weight': 30}] 
+0

因此,您應該展示OP如何將數據轉置爲假設它可能很大。你的是最好的選擇國際海事組織只使用字典 – JBernardo

+0

我的猜測是數據採用了DeepSpace建議的格式,而OP則向他們申請了一些他向我們顯示的格式。 – gboffi

0

你可以使用itertools.compress和字典解析:

>>> import itertools 

>>> dct = {'Sex': ['Male', 'Male', 'Female', 'Female', 'Male'], 
...  'Height': [100, 200, 150, 80, 90], 
...  'Weight': [20, 60, 40, 30, 30]} 

>>> mask = [item == 'Male' for item in dct['Sex']] 

>>> new_dict = {key: list(itertools.compress(dct[key], mask)) for key in dct} 
>>> new_dict 
{'Height': [100, 200, 90], 
'Sex': ['Male', 'Male', 'Male'], 
'Weight': [20, 60, 30]} 
0

可以使用大熊貓數據框(install包第一)

>>> data = pandas.DataFrame(
    {'Sex':['Male','Male','Female','Female','Male'], 
    'Height': [100,200,150,80,90], 
    'Weight': [20,60,40,30,30]} 
) 

>>> data[data['Sex'] == 'Male'] 
    Height Sex Weight 
0  100 Male  20 
1  200 Male  60 
4  90 Male  30 

這會更像一個數據庫,並可以過濾了很多東西毫不費力。

1

使用該解決方案collections.defaultdictzip()功能:

d = { 
    'Sex':['Male','Male','Female','Female','Male'], 
    'Height': [100,200,150,80,90], 
    'Weight': [20,60,40,30,30] 
} 

result = collections.defaultdict(list) 
for s,h,w in zip(d['Sex'], d['Height'], d['Weight']): 
    if s == 'Male': 
     result['Sex'].append(s) 
     result['Height'].append(h) 
     result['Weight'].append(w) 

print(dict(result)) 

輸出:

{'Sex': ['Male', 'Male', 'Male'], 'Weight': [20, 60, 30], 'Height': [100, 200, 90]} 
0

就個人而言,我會使用對象的列表,而不是,有在同一個對象的相關屬性,這方式:

people = [{"Sex": "Male", "Height": 100, "Weight": 20}, {...}, ...] 

我會轉換爲一個列表這樣(assumin克名單在你的字典都具有相同的尺寸):

list = [] 
for i in range(len(dict["Sex"])): 
    list.append({k: v[i] for k, v in dict.iteritems()}) 

或者使用d.items(),如果你是在Python 3.x的

然後你就可以通過鍵值,更多的細節here

0

容易過濾列表我只是把這個在這裏,因爲我寫的也無妨。它會根據您的字典在內存中創建一個數據庫,然後您可以根據您的需要進行查詢(靈活地按照您的注意事項)以獲得您想要的結果。

dict_ = {'Sex': ['Male', 'Male', 'Female', 'Female', 'Male'], 
     'Height': [100, 200, 150, 80, 90], 
     'Weight': [20, 60, 40, 30, 30]} 

import sqlite3 

conn = sqlite3.connect(':memory:') 
curs = conn.cursor() 
column_headers = [x for x in dict_] # the keys are the headers 
column_types = ('' for x in dict_) 
header_creation = ', '.join([' '.join(x) for x in zip(column_headers, column_types)]) 
curs.execute("CREATE TABLE temp ({})".format(header_creation)) 
bindings = ','.join('?' * (header_creation.count(',') + 1)) 
result_insertion = "INSERT INTO temp ({}) VALUES ({})".format(', '.join(column_headers), bindings) 
for i, item in enumerate(dict_[column_headers[0]]): 
    values = [item] 
    for j in column_headers[1:]: 
     values.append(dict_[j][i]) 
    curs.execute(result_insertion, values) 
conn.commit() 

condition = 'weight >= 40' 

out = curs.execute('SELECT * FROM temp{}'.format(' WHERE {}'.format(condition) if condition else ';')).fetchall() 
dict_out = {} 
for i, k in enumerate(column_headers): 
    dict_out[k] = [x[i] for x in out] 
print(dict_out) # {'Sex': ['Male', 'Female'], 'Weight': [60, 40], 'Height': [200, 150]}