从文本行和重复项创建词典列表

时间:2016-06-01 10:35:00

标签: list python-2.7 dictionary

陷入相对简单的任务。 有文本文件,需要做一个词典列表。如果该行的第一项是相同的,则来自其他行的项应属于同一字典。 请参阅文本文件和首选结果。

.txt的

739883332,amenity,recycling
739883346,amenity,recycling
835250417,payment:maestro,yes
835250417,payment:mastercard,yes
835250417,payment:visa,yes
3259847948,recycling:cans,no
3259847948,recycling:clothes,no

到目前为止,我已经......

for i in line:          
    i=i.strip() 
    i=i.split(',')
    ID=i[0] 
    key=i[1]
    val=i[2]
    dict['ID']=ID
    dict[key]=val

首选结果:

[{'ID':739883332},{'amenity':'recycling'}]
[{'ID':739883346},{'amenity':'recycling'}]
[{'ID':835250417},{'payment:maestro':'yes'},{'payment:mastercard':'yes'},{'payment:visa':'yes'}]
[{'ID':3259847948},{'recycling:cans':'no'},{'recycling:clothes':'no'}]

1 个答案:

答案 0 :(得分:0)

刚刚找到解决方案:

def merge_lists(d1list, d2list, key):
merged = {}
for item in d1list+d2list:
    if item[key] in merged:
        merged[item[key]].update(item)
    else:
        merged[item[key]] = item
return [val for (_, val) in merged.items()]

for i in line:
    dict={}
    i=i.strip() 
    i=i.split(',')
    ID=i[0] 
    key=i[3]
    val=i[4]    
    dict['nodeID:']=ID
    dict[key]=val
    if ID not in list:
        list.append(ID)
        d1list.append(dict)
    else:
        d2list.append(dict)

final_list = merge_lists(d1list, d2list, 'nodeID:') 

非常感谢代码优化说明。