2014-03-07 96 views
0

Python Splunk SDK中,ResultsReader object提供了一個可迭代對象,該對象在訪問時返回OrderedDict。我想將包含在OrderedDict中的值存儲到一個集合中,以針對預期值列表執行集合減法。我很難找到一種方式來訪問OrderedDict中的值,這樣我就可以將它們存儲到一個集合中。存儲OrderedDict值以在Python中設置

代碼示例:

kwargs_search = {"exec_mode": "normal"} 
searchquery = "search index=* earliest=-1d| stats values(host)" 

job = service.jobs.create(searchquery, **kwargs_search) 
for result in results.ResultsReader(job.results()): 
    print result 

返回:

OrderedDict([('values(host)', ['host1', 'host2', ... 'hostN'])]) 

'hostN'值是那些我想在一組存儲。

我已經試過:

actual_hosts = set() 
for result in results.ResultsReader(job.results()): 
    actual_hosts.add(result) 

將返回:

Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
TypeError: unhashable type: 'OrderedDict' 

什麼是完成我試圖在這裏的最佳方式是什麼?打開任何想法。

回答

1

如果每個值在OrderedDict是一個列表(如張貼的例子),然後results.values()是一個列表(或迭代,在python3)名單。在這種情況下,你可以反覆地將它們添加到組:

actual_hosts = set() 
for result in results.ResultsReader(job.results()): 
    for hosts in results.values(): 
     actual_hosts.update(hosts) 

如果每個值是一個字符串,內環是沒有必要的,你可以添加results.values()在組直接:

actual_hosts = set() 
for result in results.ResultsReader(job.results()): 
    actual_hosts.update(results.values()) 
+0

所以,我覺得這是非常,非常接近我要找的。您的第一個方法會創建以下集合: 'set(['host1',...'hostN'])'這似乎是該集合中的一個列表。在這種情況下,actual_hosts中的'host1'返回'False'。 你的第二個方法返回錯誤'TypeError:unhashable type:'list'',所以我需要在存儲到集合之前檢索所有列表元素。 – voteblake

+0

'set(['host1',...'hostN'])'是標準集合表示,它不是集合內的列表。如果這就是你所得到的,'actual_hosts'中的'host1'應該是'True' ...如果OrderedDict的結構不同,那麼第二個例子就可以工作,所以它不相關(我在第一次不確定結構是什麼,所以我包括第二個例子)。 – shx2

+0

謝謝你,你是絕對正確的,用調試器完成它,並能夠得到我期待的結果。 – voteblake

0

result.values()應該給你一部分['host1',..

0

創建從dict的值(這是同樣與OrderedDict)的一組的一個例子:

d = { 
    'a': [1, 2, 3], 
    'b': [2, 3, 4] 
} 

hosts = set().union(*d.itervalues()) 
# set([1, 2, 3, 4]) 

然後延伸到:

from itertools import chain 
hosts = set().union(*chain.from_iterable(res.values() for res in results.ResultsReader(job.results()))) 

的顯式循環和更新更好雖然:)