0

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?

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.