简体   繁体   English

如何将字典中的字符串值转换为python中的列表?

[英]How to convert String values in a dictionary to a list in python?

I am trying to read contents from file which has the following content 我正在尝试从具有以下内容的文件中读取内容

XXX f,d,c,e
DDD f,d,c,g
ZZZ f,d,h,g
KKK c,c,d,d

I have to read this as a dictionary in the below format. 我必须将其读作以下格式的字典。 The below should be my final output - 以下应该是我的最终输出 -

{'XXX': ['f','d','c','e'], 'DDD': ['f','d','c','g'], 'ZZZ': ['f','d','h','g'], 'KKK': ['c','c','d','d']}

But I managed to read it as dictionary in the below format. 但我设法以下面的格式将其作为字典阅读。 But the values are not in list format. 但这些值不是列表格式。 Current output 电流输出

{'XXX': 'f,d,c,e', 'DDD': 'f,d,c,g', 'ZZZ': 'f,d,h,g', 'KKK': 'c,c,d,d'}

Can someone help to convert the values as list or directly read it as list from file? 有人可以帮助将值转换为列表或直接从文件中将其作为列表读取吗?

Use str.split(",") 使用str.split(",")

Ex: 例如:

d = {'XXX': 'f,d,c,e', 'DDD': 'f,d,c,g', 'ZZZ': 'f,d,h,g', 'KKK': 'c,c,d,d'}
d = {k: v.split(",") for k,v in d.items()}
print(d)

Output: 输出:

{'XXX': ['f', 'd', 'c', 'e'], 'ZZZ': ['f', 'd', 'h', 'g'], 'KKK': ['c', 'c', 'd', 'd'], 'DDD': ['f', 'd', 'c', 'g']}

Try this in one line: 在一行中尝试这个:

a = '''XXX f,d,c,e
    DDD f,d,c,g
    ZZZ f,d,h,g
    KKK c,c,d,d'''

{k:v.split(',') for k,v in {l.split()[0]:l.split()[1] for l in a.split('\n')}.items()}

the out put: 输出:

{'XXX': ['f', 'd', 'c', 'e'],
 'DDD': ['f', 'd', 'c', 'g'],
 'ZZZ': ['f', 'd', 'h', 'g'],
 'KKK': ['c', 'c', 'd', 'd']}

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

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