Python:将元组列表转换为dicts列表

时间:2014-02-28 20:59:51

标签: python json d3.js bundle-layout

我正试图弄乱this D3 visualization :(其代码为here

enter image description here

但是,我在尝试以正确的格式获取数据方面遇到了麻烦。

数据(供参考)必须采用以下格式:

[
{"name":"something 1","size":number 1,"imports":["thing 1","thing 2","thing 3","thing 4","thing 5","thing 6"]},
{"name":"something 2","size":number 2,"imports":["thing 1","thing 2","thing 3","thing 4","thing 5"]}
]

现在,我的数据(截至目前)采用格式(使用nltk收集):

[('would', 'MD'), ('said', 'VBD'), ('like', 'IN'), ('man', 'NN')]

使用defaultdict,我能够使用以下行转换数据:

pos = [('would', 'MD'), ('said', 'VBD'), ('like', 'IN'), ('man', 'NN')]
d = defaultdict( list )
for a, b in pos:
    d[b].append(a)
d = [ {b, d[b]} for b in d ] 

为:

[
{'MD': ['would']}, 
{'NN': ['man']}, 
{'IN': ['like']}, 
{'VBD': ['would']}
]

我不太清楚如何继续或如何以正确的格式获取它。任何帮助将不胜感激。谢谢!

编辑:我应该更清楚;我的预期输出是这样的:

[
{'name': 'man', 'POS':['MD']}
]

2 个答案:

答案 0 :(得分:1)

修改

oldList = [('would', 'MD'), ('said', 'VBD'), ('like', 'IN'), ('man', 'NN')]
newList = [{'name':a, 'POS':[b]} for a,b in list]

newList == [{'name': 'would', 'POS': ['MD']}, {'name': 'said', 'POS': ['VBD']}, {'name': 'like', 'POS': ['IN']}, {'name': 'man', 'POS': ['NN']}]

转换为词典列表:

list = [('would', 'MD'), ('said', 'VBD'), ('like', 'IN'), ('man', 'NN')]
newlist = []
for a,b in list:
    newlist.append({a:b})

newlist == [{'would': 'MD'}, {'said': 'VBD'}, {'like': 'IN'}, {'man': 'NN'}]

或者将每个元组添加到一个字典中:

list = [('would', 'MD'), ('said', 'VBD'), ('like', 'IN'), ('man', 'NN')]
newlist = {a:b for a, b in list}

newlist == {'said': 'VBD', 'like': 'IN', 'would': 'MD', 'man': 'NN'}

答案 1 :(得分:1)

这样的东西?

[{k, v} for k, v in list]