T.J. Kolberg
T.J. Kolberg

Reputation: 39

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:

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?

Upvotes: 0

Views: 107

Answers (1)

esramish
esramish

Reputation: 327

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))

Upvotes: 1

Related Questions