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

Adding Two Lists into One Dictionary (Python)

I have two lists, one containing a list of keys, and another containing the values to be assigned to each key, chronologically, by key.

For example;

key_list = ['cat', 'dog', 'salamander']
value_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

I’m looking to make a quick method that takes these two lists, and from it can spit out a dictionary that looks like this:

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

key_value_pairs = {
    'cat': [1, 4, 7],
    'dog': [2, 5, 8],
    'salamander': [3, 6, 9]
}

Regardless of the length of the values, I’m looking for a way to just iterate through each value and amend them to a dictionary containing one entry for each item in the key_list. Any ideas?

>Solution :

key_value_pairs = {k: [v for v_i, v in enumerate(value_list) if v_i % len(key_list) == k_i] for k_i, k in enumerate(key_list)}

Edit: that’s a fun one-liner, but it has worse time complexity than the following solution, which doesn’t use any nested loops:

lists = [[] for _ in key_list]
for i, v in enumerate(value_list):
    lists[i % len(key_list)].append(v)

key_value_pairs = dict(zip(keys, lists))
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