0

我有如下数据:

data = """
a:b,c,a
b:c,d
c:b
d:c
"""

我想将此字符串转换为这样的字典:

data_dict = {'a':['b','c','a'],'b':['c','d'],'c':['b'], 'd':['c']}

我试过了:

data_list = data.strip('\n').split('\n')
data_str = ", ".join( repr(i) for i in data_list )
data_dict = {}

for i in range(len(data_list)):
    keys, values = data_list[i].split(':')
    key = keys.split('\t')
    value = values.split('\t')
    data_dict = dict(zip(key, value))
    print data_dict

但不幸的是,我得到了:

{'a':'b,c,a'}
{'b':'c,d'}
{'c':'b'} 
{'d':'c'}

任何人都可以帮助我吗?非常感谢。

4

1 回答 1

1

怎么样:

>>> kvs = (line.split(":", 1) for line in data.strip().splitlines())
>>> d = {k: v.split(",") for k,v in kvs}
>>> d
{'a': ['b', 'c', 'a'], 'c': ['b'], 'b': ['c', 'd'], 'd': ['c']}
于 2013-07-19T05:31:15.453 回答