[英]Create a dictionary from a list of key and multi list of values in Python
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]第一个数字是 5,包含 4 个项目的列表的值等于 x = x + 3,依此类推 [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第二个列表的第一个数字等于:x = 5 + 14,并且里面的值仍然如上 x = x +3
[[5, 8, 11, 14], [19, 22, 25, 28], [33, 36, 39, 42], [47, 50, 53, 56], [61, 64, 67, 70]] [[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我尝试了另一种方法,例如使用
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: output 是:
{<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?并在不使用
zip
方法的情况下创建字典collections
?
Thank you so much for your attention and participation.非常感谢您的关注和参与。
Sure, you can use enumerate
but I wouldn't say it is in anyway better or worse than the zip
based solution:当然,您可以使用
enumerate
但我不会说它比基于zip
的解决方案更好或更差:
collections = {}
for idx, key in enumerate(list_keys):
collections[key] = list_value[idx]
print(collections)
Output: 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:此外,您不需要单独创建值列表,您可以像 go 一样创建字典:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.