简体   繁体   English

解析列表项并使用理解返回字典

[英]Parsing list items and returning a dictionary using comprehension

I have a two-items list which I need to process. 我有一个两项清单,我需要处理。 Those items are retrieved from a database, so the are actually header: value pairs but they are unparsed. 这些项是从数据库中检索的,因此实际上是标题:值对但它们是未解析的。 They are strings separated by tabs, so the list looks like this: 它们是由制表符分隔的字符串,因此列表如下所示:

my_list = ['header1\theader2\theader3\theader4', 'val1\tval2\tval3\tval4']

I need to create dict from the key - value pairs. 我需要从键 - 值对创建dict。 Currently I do it with list comprehension: 目前我用列表理解来做到这一点:

keys = [k.strip() for k in my_list[0].split('\t')]
vals = [v.strip() for v in my_list[1].split('\t')]
return dict(zip(keys, vals))

I think there might be a way doing that using dict comprehension instead, but I couldn't get how. 我认为可能有一种方法可以使用dict理解来实现,但我无法理解。 Is it possible to do parse the list items and return a dictionary with a one-liner or a more pythonic way? 是否可以解析列表项并返回带有单行或更加pythonic方式的字典?

Try something like this 尝试这样的事情

dict_comp = {k.strip():v.strip() for k,v in 
               zip(my_list[0].split('\t'), my_list[1].split('\t'))}

I find the solution below the most elegant one: 我找到了最优雅的解决方案:

dict_comp = dict(zip(*map(lambda x: x.split('\t'), my_list)))
print(dict_comp)  # -> {'header1': 'val1', 'header2': 'val2', 'header3': 'val3', 'header4': 'val4'}

Alternatively, the lambda can be substituted by a generator expression : 或者, lambda可以用生成器表达式代替:

dict_comp = dict(zip(*(x.split('\t') for x in my_list)))

and if the strings do not contain any spaces, it can be shortened even further to: 如果字符串不包含任何空格,则可以进一步缩短到:

dict_comp = dict(zip(*map(str.split, my_list)))  # kudos @Chris_Rands

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM