Reputation: 659
I have 2 lists of equal number of indexes in it.
eg:
hst = ['host1', 'host2', 'host1', 'host2']
err = ['Tomcat', 'Disk Space', 'MySQL', 'Apache']
I want to convert this into a dictionary in the below format:
{'host1': ['Tomcat', 'MySQL'],
'host2' : ['Disk Space', 'Apache'],
}
Upvotes: 1
Views: 69
Reputation: 23203
Simple EAFP approach:
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
Upvotes: 2
Reputation: 180391
A collections.defaultdict is the most efficient way to group your data handling repeated keys:
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)
Output:
defaultdict(<type 'list'>, {'host2': ['Disk Space', 'Apache'],
'host1': ['Tomcat', 'MySQL']})
Upvotes: 2
Reputation: 90889
I would use zip()
function and dict.setdefault()
. Example -
dic = {}
for x,y in zip(hst,err):
dic.setdefault(x,[]).append(y)
Demo -
>>> 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()
function combines the two lists at their corresponding indexes (till the index of the smallest array, but this is not an issue for you since you say I have 2 lists of equal number of indexes in it. ) , so for first iteration you would get x as 'host1'
and y as 'Tomcat'
, for second iteration you would get x as 'host2'
and y as 'Disk Space'
, etc.
dict.setdefault(key, default)
sets the key with default value and returns the default value if the key does not exist in the dictionary, and if the key exists in the dictionary it returns its value.
Upvotes: 3