2016-12-01 182 views
2

輸入查找定義的列表內的字典的鍵值是頭看起來像簡單的CSV文件:,通過匹配字典值

dc,environment,type,component,fqdn,distribution,release 
1,prod,web,fo,aa,ubuntu,14.04.5 

它是由csv.DictReader(csv)裝入server_list

def get_server(**kwargs): 
    f = open("servers.dat", 'rt') 
    try: 
     reader = csv.DictReader(f) 
     server_list = [] 
     for row in reader: 
      server_list.append(row) 
    finally: 
     f.close() 

列表包括:

{'component': 'a', 'dc': '1', 'fqdn': 'aa', 'environment': 'prod', 'release': '14.04.5', 'distribution': 'ubuntu', 'type': 'web'} 
{'component': 'a', 'dc': '1', 'fqdn': 'bb', 'environment': 'prod', 'release': '14.04.5', 'distribution': 'ubuntu', 'type': 'web'} 
{'component': 'b', 'dc': '1', 'fqdn': 'cc', 'environment': 'prod', 'release': '12.04.5', 'distribution': 'ubuntu', 'type': 'web'} 
{'component': 'a', 'dc': '1', 'fqdn': 'dd', 'environment': 'test02', 'release': '14.04.5', 'distribution': 'ubuntu', 'type': 'web'} 

我想獲得v當輸入將是例如fqdn時。來自python函數的例如dc = 1 and component = aget_foo(dc='1', component='a', environment=None)defined def get_foo(**kwargs)或不同。只有結果是必需的。

因此,在這種情況下,預期的結果是所有的這些線,除了第3位。

謝謝你,你的dict S,這樣的事情的清單

+0

這是一個文件的內容通過關鍵字參數呢?這不是一個有效的數據結構。還包括你有什麼嘗試。 –

+0

歡迎使用stackoverflow。爲了獲得幫助,你需要展示1)你的輸入是什麼樣的,2)期望的輸出是什麼樣的,3)你的需求,最重要的是:4)你試過了什麼。見https://stackoverflow.com/help/how-to-ask –

+0

你是對的。問題已更新。謝謝你的建議。 – Neurobion

回答

3

更普遍

def get_foo(l, **kwargs): 
    return [x['fqdn'] for x in l if all(x[i] == kwargs[i] for i in kwargs)] 

,這將拋出一個KeyError例外是你在字典x

+0

嗨@PatrickHaugh非常感謝。它按預期工作。這是非常優雅的解決方案。我感謝您的幫助。 – Neurobion

0

你的問題指出:

>>> a = [{'component': 'a', 
      'dc': '1', 
      'distribution': 'ubuntu', 
      'environment': 'prod', 
      'fqdn': 'aa', 
      'release': '14.04.5', 
      'type': 'web'}, 
     {'component': 'a', 
      'dc': '1', 
      'distribution': 'ubuntu', 
      'environment': 'prod', 
      'fqdn': 'bb', 
      'release': '14.04.5', 
      'type': 'web'}, 
     {'component': 'b', 
      'dc': '1', 
      'distribution': 'ubuntu', 
      'environment': 'prod', 
      'fqdn': 'cc', 
      'release': '12.04.5', 
      'type': 'web'}, 
     {'component': 'a', 
      'dc': '1', 
      'distribution': 'ubuntu', 
      'environment': 'test02', 
      'fqdn': 'dd', 
      'release': '14.04.5', 
      'type': 'web'}] 

使用list comprehension語法,你可以永遠只是過濾的dict是清單

>>> [x['fqdn'] for x in a if x['dc'] == '1' and x['component'] == 'a'] 
['aa', 'bb', 'dd'] 

將其封裝在一個函數中:

def get_foo(dlist, dc='1', component='a'): 
    return [dv['fqdn'] for dv in dlist 
      if dv['dc'] == dc 
      and dv['component'] == component] 

然後:

>>> get_foo(a) 
['aa', 'bb', 'dd'] 
+0

當條件數量取決於參數時,我正在尋找解決方案。如果我需要比較3個鍵而不是2個和它們的值,或者4個等,我不想編輯語句。它應該是「動態的」。 – Neurobion

+0

通過@PatrickHaugh答案是你在找什麼,我想。在布爾值的生成器表達式上的「all」就像是一起處理大量的條件。 – wildwilhelm