Python词典:将多个值列表合并为一个唯一值列表

时间:2013-07-30 18:11:12

标签: python python-2.7 dictionary

我只是在使用Python 2.7学习Python。我有一个包含两列的csv文件。列是:

Coll_id:条目可以是单个收集者,也可以是群组

Participant_Coll_id:如果Coll_id是单个收集器,则该值将为null。如果Coll_id是一个组,那么该组中的每个参与者将只有一行。

示例在这里:

Coll_id,Participant_Coll_id<br>
ARA,ARG  
ARA,RAT  
ARG,NULL  
BRSAR,SGMB  
BRSAR,SANTM  
BRSAR,CRSR  
BRSAR,RAT  
CRSR,NULL  
DBY,NULL  
HZIE,NULL  
RAT,NULL  
SANTM,NULL  
SGMB,NULL  
ARG,NULL  
DRS,CRSR  
DRS,RAT  
DRS,ARG  

对于每个收集器(coll_id),我正在尝试创建他们收集的所有其他收集器的列表。我试图将代码拉到一起来执行以下操作,现在它非常接近:

#This is giving me a dictionary with each COLL_ID having a list of PARTICIPANT_COLL_IDs

with open('colls_mv1.csv', 'r') as f:
    reader = csv.DictReader(f, ['COLL_ID', 'PARTICIPANT_COLL_ID'])
    data1 = defaultdict(list)

    for line in reader:
        data1[line['COLL_ID']].append(line['PARTICIPANT_COLL_ID'])


#And this is giving me a dictionary with each PARTICIPANT_COLL_ID having a list of COLL_IDs
with open('colls_mv1.csv', 'r') as f:
    reader = csv.DictReader(f, ['COLL_ID', 'PARTICIPANT_COLL_ID'])
    data2 = defaultdict(list)

    for line in reader:
        if line['PARTICIPANT_COLL_ID'] != 'NULL':
            data2[line['PARTICIPANT_COLL_ID']].append(line['COLL_ID'])

dict3 = {k: [data1[i] for i in v] for k, v in data2.items()}

print dict3

我得到以下输出:

{'SGMB': [['SGMB', 'SANTM', 'CRSR', 'RAT']], 'CRSR': [['SGMB', 'SANTM', 'CRSR', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'RAT': [['ARG', 'RAT'], ['SGMB', 'SANTM', 'CRSR', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'PARTICIPANT_COLL_ID': [['PARTICIPANT_COLL_ID']], 'ARG': [['ARG', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'SANTM': [['SGMB', 'SANTM', 'CRSR', 'RAT']]}

我想要的是为每个键合并值列表,删除重复项并从值列表中删除键:

{'SGMB': ['SANTM', 'CRSR', 'RAT'], 'CRSR': ['SGMB', 'SANTM', 'RAT', 'ARG'], 'RAT': ['ARG', 'SGMB', 'SANTM', 'CRSR'], 'PARTICIPANT_COLL_ID': [['PARTICIPANT_COLL_ID']], 'ARG': ['RAT', 'CRSR'], 'SANTM': ['SGMB', 'CRSR', 'RAT']}

1 个答案:

答案 0 :(得分:1)

迭代列表,删除密钥和重复数据删除

>>> res = {'SGMB': [['SGMB', 'SANTM', 'CRSR', 'RAT']], 'CRSR': [['SGMB', 'SANTM', 'CRSR', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'RAT': [['ARG', 'RAT'], ['SGMB', 'SANTM', 'CRSR', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'PARTICIPANT_COLL_ID': [['PARTICIPANT_COLL_ID']], 'ARG': [['ARG', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'SANTM': [['SGMB', 'SANTM', 'CRSR', 'RAT']]}
>>> newres = {k: list({x for t in v for x in t if x != k}) for k, v in res.iteritems()}
>>> newres
{'SGMB': ['CRSR', 'SANTM', 'RAT'], 'CRSR': ['SANTM', 'SGMB', 'RAT', 'ARG'], 'RAT': ['CRSR', 'SANTM', 'SGMB', 'ARG'], 'PARTICIPANT_COLL_ID': [], 'ARG': ['CRSR', 'RAT'], 'SANTM': ['CRSR', 'RAT', 'SGMB']}

演示:http://ideone.com/87HKM9