简体   繁体   English

在Python中将新行分隔的值从列表转换为字典

[英]Convert new line separated values from list to dictionary in Python

I have a list of alphabets separated by \\n . 我有一个用\\n分隔的字母列表。

mylist = ['a\n','b c d e\n', 'f g h i j\n', 'k l m\n', 'n o\n', 'p q r s\n', 't\n', 'u v w x y z\n'] 

I want to convert this into a dictionary of format: 我想将其转换为格式的字典:

mydict= {
a: {}
b: {c, d, e}
f: {g, h, i, j}
k: {l, m}
n: {o}
p: {q, r, s}
t: {}
u: {v, w, x, y, z}
}

What is the best way to achieve this in Python? 用Python实现此目标的最佳方法是什么?

Thank you in advance. 先感谢您。

类似于以下内容的东西应该起作用:

{x[0]: set(x[1:]) for x in map(str.split, mylist)}

dict comprehension: dict理解:

>>> mydict = {x[0]:x[1:].strip().split() for x in mylist}
>>> mydict
{'p': ['q', 'r', 's'], 'n': ['o'], 'f': ['g', 'h', 'i', 'j'], 'a': [], 't': [], 'u': ['v', 'w', 'x', 'y', 'z'], 'b': ['c', 'd', 'e'], 'k': ['l', 'm']}

Given: 鉴于:

mylist = ['a\n','b c d e\n', 'f g h i j\n', 'k l m\n', 'n o\n', 'p q r s\n', 't\n', 'u v w x y z\n']

You can use a dict of sets: 您可以使用集合的字典:

mydict={}
for e in mylist:
    li=e.split()
    mydict[li[0]]=set(li[1:])

>>> mydict
{'a': set([]), 'b': set(['c', 'e', 'd']), 'f': set(['i', 'h', 'j', 'g']), 'k': set(['m', 'l']), 'n': set(['o']), 'p': set(['q', 's', 'r']), 'u': set(['y', 'x', 'z', 'w', 'v']), 't': set([])}

And if you want your exact format: 如果您想要确切的格式:

>>> print '\n'.join(['{}: {}'.format(k, '{{{}}}'.format(', '.join(list(v)))) for k, v in mydict.items()]) 
a: {}
p: {q, s, r}
b: {c, e, d}
u: {y, x, z, w, v}
t: {}
f: {i, h, j, g}
k: {m, l}
n: {o}

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

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