I have the following list:
hc_ips = ['cnhi.test1.com', '1821', 'test.aiam-test.com', '3136', 'test.test-aiops.com', '3451', 'test-apt.test-dh.com', '3136', 'test.test-aiops.com', '52174', 'test.aiam-test.com', '54167', 'test-apt.test-dh.com', '54167']
which I would like to become dictionary with list as values.
Expected output:
{'cnhi.test1.com':['1821'], 'test.aiam-test.com': ['3136','54167'], 'test.test-aiops.com': ['3451','52174'], 'test-apt.test-dh.com': ['3136','54167']}
Items with the same key need to be consolidated together in a single list.
I’ve tried:
dct = {hc_ips[i]: hc_ips[i + 1] for i in range(0, len(hc_ips), 2)}
but this is only making dictionary like:
{'cnhi.test1.com': '1821', 'test.aiam-test.com': '54167', 'test.test-aiops.com*': '52174', 'test-apt.test-dh.com': '54167'}
>Solution :
The problem is that a dictionary can only have one value per key, so when your dict comprehension encounters a key that already exists, it overwrites the old value with the new one.
Also notice that the values in your expected output are lists, not strings.
So to answer your question, you need to create a dictionary where the values are lists. If you come across a key that already exists, add the value to the existing list instead of creating a new one.
dct = dict()
for key, value in zip(hc_ips[::2], hc_ips[1::2]):
if key in dct:
dct[key].append(value)
else:
dct[key] = [value]
And you get:
{'cnhi.test1.com': ['1821'],
'test.aiam-test.com': ['3136', '54167'],
'test.test-aiops.com': ['3451', '52174'],
'test-apt.test-dh.com': ['3136', '54167']}
Alternatively, you can use collections.defaultdict, which will automatically create a default value the first time you access a key, so you can simply .append(value).
import collections
dct = collections.defaultdict(list)
for key, value in zip(hc_ips[::2], hc_ips[1::2]):
dct[key].append(value)
which gives:
defaultdict(list,
{'cnhi.test1.com': ['1821'],
'test.aiam-test.com': ['3136', '54167'],
'test.test-aiops.com': ['3451', '52174'],
'test-apt.test-dh.com': ['3136', '54167']})