[英]Using a list comprehension used as a conditional filter nested in a dictionary comprehension
I am trying to create a dictionary of dictionaries that is being created by filtering a known dictionary and the conditional comes from a list.我正在尝试创建一个字典字典,该字典是通过过滤已知字典来创建的,并且条件来自一个列表。 This would be dynamic, so the data within the list and the known dictionary will constantly change.这将是动态的,因此列表和已知字典中的数据将不断变化。
list = {5: ('t', 'a'), 7: ('s', 'o')}
known_dict = {('s', 'a'): 105, ('s', 'e'): 2, ('s', 'h'): 5, ('t', 'a'): 21,
('t', 'e'): 8, ('t', 'h'): 21}
Given the above, I am trying to create a dictionary where the keys are the first character of the tuples in the list, and the values are the corresponding first character tuples from the known dictionary.鉴于上述情况,我正在尝试创建一个字典,其中键是列表中元组的第一个字符,值是已知字典中相应的第一个字符元组。
desired_output = {s: {('s', 'a'): 105, ('s', 'e'): 2, ('s', 'h'): 5},
t: {('t', 'a'): 21, ('t', 'e'): 8, ('t', 'h')}}
The code I have to try to achieve this is:我必须尝试实现的代码是:
desired_output = {
key[0]: {
key: value for key, value in known_dict.items()
if key[0] == [a for a,b in list.values()]
}
for key in known_dict
}
The issue of is that when the list comprehension occurs, the result is a list which and not individual characters, so my result is an empty dictionary because the conditional is not met.问题是当列表理解发生时,结果是一个列表,而不是单个字符,所以我的结果是一个空字典,因为条件不满足。
If there is something I am missing or if there is a different approach that I should consider, please let me know.如果我遗漏了什么或者我应该考虑其他方法,请告诉我。
The following should work.以下应该工作。 Iterate over the values in "list"
(which you shold rename) and collect the items from "known_dict"
along the way, not the other way round:遍历"list"
中的值(您应该重命名)并沿途从"known_dict"
收集项目,而不是相反:
desired_output = {
v[0]: {k_: v_ for k_, v_ in known_dict.items() if k_[0]==v[0]}
for v in list.values()
}
# {'t': {('t', 'a'): 21, ('t', 'e'): 8, ('t', 'h'): 21},
# 's': {('s', 'a'): 105, ('s', 'e'): 2, ('s', 'h'): 5}}
Sidenote: "list"
is a terrible variable name.旁注: "list"
是一个糟糕的变量名。 First, it shadows the built-in type list
.首先,它隐藏了内置类型list
。 Second, you are using it for a dict
.其次,您将其用于dict
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.