2015-09-25 175 views
1

我有2列表中有相同數量的索引。Python列表到詞典

eg: 
hst = ['host1', 'host2', 'host1', 'host2'] 
err = ['Tomcat', 'Disk Space', 'MySQL', 'Apache'] 

我想這個轉換成字典在下面的格式:

{'host1': ['Tomcat', 'MySQL'], 
'host2' : ['Disk Space', 'Apache'], 
} 

回答

3

我會用zip()功能和dict.setdefault()。示例 -

dic = {} 
for x,y in zip(hst,err): 
    dic.setdefault(x,[]).append(y) 

演示 -

>>> hst = ['host1', 'host2', 'host1', 'host2'] 
>>> err = ['Tomcat', 'Disk Space', 'MySQL', 'Apache'] 
>>> dic = {} 
>>> for x,y in zip(hst,err): 
...  dic.setdefault(x,[]).append(y) 
... 
>>> dic 
{'host2': ['Disk Space', 'Apache'], 'host1': ['Tomcat', 'MySQL']} 

zip()功能在其相應的指標結合了兩個列表(直到最小的數組的索引,但這不是你的問題,因爲你比如我有兩個列表中有相同數量的索引),所以對於第一次迭代,您將得到x爲'host1',y爲'Tomcat',對於第二次迭代,您將得到x爲'host2' y爲'Disk Space'等。

dict.setdefault(key, default)設置密鑰的默認值,並返回默認值,如果密鑰不存在於字典中,並且密鑰存在於字典中,則返回其值。

2

一個collections.defaultdict是最有效的方式將數據分組處理重複鍵:

from collections import defaultdict 

d = defaultdict(list) 
hst = ['host1', 'host2', 'host1', 'host2'] 
err = ['Tomcat', 'Disk Space', 'MySQL', 'Apache'] 

for k,v in zip(hst,err): 
    d[k].append(v) 

輸出:

defaultdict(<type 'list'>, {'host2': ['Disk Space', 'Apache'], 
          'host1': ['Tomcat', 'MySQL']}) 
2

簡單EAFP方法:

hst = ['host1', 'host2', 'host1', 'host2'] 
err = ['Tomcat', 'Disk Space', 'MySQL', 'Apache'] 


def make_dict(hst, err): 
    d = {} 
    for h, e in zip(hst, err): 
     try: 
      d[h].append(e) 
     except KeyError: 
      d[h] = [e] 
    return d 


expected = {'host1': ['Tomcat', 'MySQL'], 'host2' : ['Disk Space', 'Apache']} 
result = make_dict(hst, err) 
assert expected == result