0

I have a list of key:

list_date = ["MON", "TUE", "WED", "THU","FRI"]

I have many lists of values that created by codes below:

list_value = list()
for i in list(range(5, 70, 14)):
    list_value.append(list(range(i, i+10, 3)))

Rules created that:

  • first number is 5, a list contains 4 items has value equal x = x + 3, and so on [5, 8, 11,1 4]

  • the first number of the second list equal: x = 5 + 14, and value inside still as above x = x +3

    [[5, 8, 11, 14], [19, 22, 25, 28], [33, 36, 39, 42], [47, 50, 53, 56], [61, 64, 67, 70]]

I expect to obtain a dict like this:

collections = {"MON":[5, 8, 11, 14], "TUE" :[19, 22, 25, 28], "WED":[33, 36, 39, 42], "THU":[47, 50, 53, 56], "FRI":[61, 64, 67, 70]}

Then, I used:

zip_iterator = zip(list_date, list_value)
collections = dict(zip_iterator)

To get my expected result.

I tried another way like using lambda function

for i in list(range(5, 70, 14)):
    list_value.append(list(range(i,i+10,3)))
    couple_start_end[lambda x: x in list_date] = list(range(i, i + 10, 3))

And the output is:

{<function <lambda> at 0x000001BF7F0711F0>: [5, 8, 11, 14], <function <lambda> at 0x000001BF7F071310>: [19, 22, 25, 28], <function <lambda> at 0x000001BF7F071280>: [33, 36, 39, 42], <function <lambda> at 0x000001BF7F0710D0>: [47, 50, 53, 56], <function <lambda> at 0x000001BF7F0890D0>: [61, 64, 67, 70]}

I want to ask there is any better solution to create lists of values with the rules above? and create the dictionary collections without using the zip method?

Thank you so much for your attention and participation.

1
  • 1
    Questions seeking to optimize working code might be a better fit for Code Review. Remember to check their on-topic and asking guidelines first though! Commented Apr 8, 2021 at 14:25

1 Answer 1

2

Sure, you can use enumerate but I wouldn't say it is in anyway better or worse than the zip based solution:

collections = {}
for idx, key in enumerate(list_keys):
    collections[key] = list_value[idx]
print(collections)

Output:

{'MON': [5, 8, 11, 14], 'TUE': [19, 22, 25, 28], 'WED': [33, 36, 39, 42], 'THU': [47, 50, 53, 56], 'FRI': [61, 64, 67, 70]}

Further, you don't need to create the value list separately, you can create the dictionary as you go along:

list_keys = ["MON", "TUE", "WED", "THU","FRI"]
collections = {}
for idx, start in enumerate(range(5, 70, 14)):
    collections[list_keys[idx]] = [i for i in range(start, start+10, 3)]
print(collections)
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.