简体   繁体   English

如何将字符串列表转换为键以给定 substring 开头的列表字典

[英]How to convert a list of strings to a dict of lists where keys start with given substring

I have a list like this:我有一个这样的列表:

list = ['ID - ISO', 'CATA - CIT', 'CATA - CIT2', 'ID - ISO6', 'CATA - CIT', 'CATA - CIT2', 'CATA - CIT6', 'CATA - CIT8']

I would like to create a dictionary like this我想创建一个这样的字典

dict = {'ID - ISO': ['CATA - CIT', 'CATA - CIT2'], 
        'ID - ISO6': ['CATA - CIT', 'CATA - CIT2', 'CATA - CIT6', 'CATA - CIT8']}

So I developed this code but when I add the values, it is not working: the values are the same for all the ids.所以我开发了这段代码,但是当我添加值时,它不起作用:所有 id 的值都是相同的。

with open("/data/myfile") as openfile:
        for line in openfile:
        for single_line in line.split('\\'):
            if line.startswith("ID"):
                 Dict[line] = None
            elif line.startswith("CATA"):
                for li in Dict:
                    Dict[li]=line
print Dict

You could use itertools.groupby() :您可以使用itertools.groupby()

from itertools import groupby
lst = ['ID - ISO', 'CATA - CIT', 'CATA - CIT2','ID - ISO6', 'CATA - CIT', 'CATA - CIT2', 'CATA - CIT6', 'CATA - CIT8']

result = {}
for k,v in groupby(lst, lambda x: x.startswith('ID')):
    if k:
        key = next(v)
    else:
        result[key] = list(v)

print(result)

Which would yield这会产生

{
 'ID - ISO': ['CATA - CIT', 'CATA - CIT2'], 
 'ID - ISO6': ['CATA - CIT', 'CATA - CIT2', 'CATA - CIT6', 'CATA - CIT8']
}

Additionally, do not call your variables after builtin types ( list , dict , tuple , etc.) - you're effectively shadowing the functionality if you do.此外,不要在内置类型( listdicttuple等)之后调用您的变量 - 如果您这样做,您实际上是在隐藏功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取值包含给定 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 的所有字典键 - How to get all dict keys where values contain given substring 如何将字符串列表转换为dict,其中只有未知索引处的某种类型才能成为键? - How do I convert a list of strings into dict where only a certain type at an unknown index can become the keys? 给定一个以字符串列表作为其值的字典,您将如何检索列表包含所有其他列表唯一的字符串的所有键? - Given a dictionary with lists of strings as their values, how would you retrieve all keys where the list contains a string unique to all other lists? 给定两个字符串列表,如何将它们转换为dict? - Given two list of strings, how can I convert them into a into a dict? 转换为 dict/type 列表,一个包含字符串列表的字符串列表? - Convert to list of dict/type, a list of strings containing lists of strings? 将字典转换为列表列表 - convert a dict to a list of lists 如何 plot 列表的键的字典,我们正在绘制列表的平均值并显示 rest 的范围?[Python] - How to plot a dict of keys to lists where we are plotting the average of the list and showing ranges of the rest?[Python] 如何将dict列表转换为两个列表? - How to convert list of dict into two lists? 如何将严格排序的字符串列表转换为dict? - How to convert a strictly sorted list of strings into dict? 当某些键重复时如何将字典列表转换为字典 - how to convert list of dict to dict when some keys repeated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM