[英]How to Create a Python dictionary with multiple values from a list?
I have a Python list like below:我有一个如下所示的 Python 列表:
['Phylum_C3.30', 'CDgu97FdFT6pyfQWZmquhFtiKrL1yp', 'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT_legend', 'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT', 'Family_E3.30', 'iKUmlH47RuphW3NbqXykn0ayizhztF', 'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG_legend', 'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG', 'Class_C2.60', 'D0RRB3F0dCl39KuEZNqfdD8q9jKzUu', 'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH_legend', 'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH']
I wish to have a dictionary where keys would be any element that starts with 'Pylum' or 'Class' or 'Order' or 'Family' or 'Genus' and values will all values following that element until the next element with 'Pylum' or 'Class' or 'Order' or 'Family' or 'Genus'.我希望有一个字典,其中键可以是任何以“Pylum”或“Class”或“Order”或“Family”或“Genus”开头的元素,并且值将是该元素之后的所有值,直到下一个带有“Pylum”的元素或“类”或“顺序”或“家族”或“属”。
For eg:例如:
The final dictionary will look like:最终的字典将如下所示:
{
"Phylum_C3.30": [
'CDgu97FdFT6pyfQWZmquhFtiKrL1yp',
'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT_legend',
'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT'
],
"Family_E3.30": [
'iKUmlH47RuphW3NbqXykn0ayizhztF',
'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG_legend',
'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG'
],
"Class_C2.60": [
'D0RRB3F0dCl39KuEZNqfdD8q9jKzUu',
'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH_legend',
'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH'
],
}
Simply loop over the list, and if a value tests as a key store that as the most 'recent' key seen, and add a list to the dictionary for that key.只需循环遍历列表,如果一个值测试为键存储,则作为最近看到的“最近”键,然后将列表添加到该键的字典中。 Then for all other non-key values add to the list associated with the last-seen key:然后将所有其他非键值添加到与最后看到的键关联的列表中:
prefixes = ('Pylum', 'Class', 'Order', 'Family', 'Genus')
output = {}
current_key = None
for elem in inputlist:
if any(elem.startswith(p) for p in prefixes):
# this is a key, add it to the output
current_key = elem
if current_key not in output:
output[current_key] = []
else:
output[current_key].append(elem)
You can tweak the way a key is handled a bit;你可以稍微调整一个键的处理方式; dropping the if current_key not in output
would result in duplicate entries overwriting previous entries.删除if current_key not in output
会导致重复条目覆盖以前的条目。 Or you could raise an exception for the if current_key in output
case if duplicate entries is supposed to be a bug.或者,如果重复条目应该是错误, if current_key in output
您可以if current_key in output
案例中为if current_key in output
引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.