将具有重复键值的两个列表转换为字典

时间:2018-11-05 20:23:36

标签: python list dictionary

list1 = ['10/20/2008', '3/25/2009', '3/26/2009', '3/28/2009', '3/28/2009', '8/23/2009', '8/23/2009']
list2 = [0,0,0,0,1,0,0]

我希望我的输出看起来像这样:

{'10/20/2008': 0, '3/25/2009':0, '3/26/2009': 0, '3/28/2009': [0,1], '8/23/2009': [0,0]}

4 个答案:

答案 0 :(得分:1)

您可以使用setdefault

list1 = ['10/20/2008', '3/25/2009', '3/26/2009', '3/28/2009', '3/28/2009', '8/23/2009', '8/23/2009']
list2 = [0, 0, 0, 0, 1, 0, 0]

result = {}
for k, v in zip(list1, list2):
    result.setdefault(k, []).append(v)

print(result)

输出

{'3/28/2009': [0, 1], '3/26/2009': [0], '10/20/2008': [0], '3/25/2009': [0], '8/23/2009': [0, 0]}

如果您希望单个项目的列表只是单个项目,请执行以下操作:

result = {k: v[0] if len(v) == 1 else v for k, v in result.items()}

输出

{'3/25/2009': 0, '3/26/2009': 0, '8/23/2009': [0, 0], '10/20/2008': 0, '3/28/2009': [0, 1]}

答案 1 :(得分:1)

一种方法是按如下方式使用defaultdict

from collections import defaultdict
res_dict = defaultdict(list)

for k, v in zip(list1, list2):
    res_dict[k].append(v)

答案 2 :(得分:0)

这不完全是仅列表实现,但应该可以完成工作。

import numpy as np
listToDict=dict()
npList1=np.array(list1)
npList2=np.array(list2)
for date in set(list1):
    listToDict[date]=list(npList2[[np.where(npList1 == date)[0]]])

答案 3 :(得分:0)

您可以使用内置的python groupby

from itertools import groupby

list1 = ['10/20/2008', '3/25/2009', '3/26/2009', '3/28/2009', '3/28/2009', '8/23/2009', '8/23/2009']
list2 = [0, 0, 0, 0, 1, 0, 0]

# Zip and sort the list in order to use them with groupby
list3 = [(x, y) for x, y in zip(list1, list2)]
list3.sort()

result = {}

# Group by date.
for value, grouper in groupby(list3, lambda x: x[0]):
    # key_value has the form (date, zero_or_one)
    key_value = grouper.next()
    # Populate result according requirements. 
    result[value] = key_value[1]
    # If more than one value for date, use a list.
    for index, kv in enumerate(grouper):
        if index == 0:
            result[value] = [result[value], kv[1]]
        else:
            result[value].append(value)

print result

结果:

{'8/23/2009': [0, 0], '3/26/2009': 0, '3/28/2009': [0, 1], '3/25/2009': 0, '10/20/2008': 0}