Reputation: 39
I have 2 lists in below format .
fa_n=[['DSS', 'DCCS2K01', 'C9790D0E', '5000', 'SPA9'], ['DSS', 'DCCS2K01', 'C9790D0E', '5000', 'SPB13']]
serv_n=[['10:00:56:00:74:79:0d:0e', '50:02:01:34:36:e4:20:gh'], ['10:00:45:00:74:79:0d:0e', '50:02:01:34:36:e4:20:gh']]
I need the following dictionary output wherein the 3rd element of sublist of fa_n will always be the key ,here its '5000' and this in turn should have a key,value pair of 4th element of fa_n and 1st element of serv_n.
Expected output: {key:{key:value}, so on }
{'5000':{'SPA9':'50:02:01:34:36:e4:20:gh'},
{'SPB13','50:02:01:34:36:e4:20:gh'}}
My code
b_dir=[]
dir_wwn=[]
for arr, fa in zip(fa_n,serv_n):
b_dir.append(f"{arr[3]} ;{arr[4]}")
dir_wwn.append(f"{arr[4]} ;{fa[1]}")
print (dict(i.split(';') for i in b_dir))
>> {'5000 ': 'SPB13'}
So i thought i would create 2 separate dicts and integrate later to one and moreover i seem to be getting the output just for the last value.
Is there an easier way of going about this?
Upvotes: 0
Views: 399
Reputation: 1142
The trouble you're running into here is that dict()
(and dictionary comprehensions as well) will favor the last key-value pair it encounters if it runs into duplicate keys, e.g.:
dict([(1,2), (1,3)]) == {1: 3}
Instead you need to add to the dictionary if it already exists like so:
result = {}
for arr, fa in zip(fa_n, serv_n):
key = arr[3]
if key in result:
result[key][arr[4]] = fa[1]
else:
result[key] = {arr[4]: fa[1]}
print result
which gives you {'5000': {'SPB13': '50:02:01:34:36:e4:20:gh', 'SPA9': '50:02:01:34:36:e4:20:gh'}}
as desired.
Upvotes: 1