Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a dictionary on the fly with list as value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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']})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading