组合具有相同键名的Python词典

时间:2012-05-16 20:28:43

标签: python

我有两个单独的Python列表,它们在各自的字典中有共同的键名。名为recordList的第二个列表包含多个具有相同键名的词典,我想要附加第一个列表clientList。以下是示例列表:

clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]

因此最终结果将是这样的,因此记录现在位于clientList内的多个词典的新列表中。

 clientList = [{'client1': [['c1','f1'], [{'rec_1':['t1','s1']},{'rec_2':['t2','s2']}]]}, {'client2': [['c2','f2']]}]

看起来很简单,但我很难找到一种方法来迭代这两个字典使用变量来找到它们匹配的位置。

3 个答案:

答案 0 :(得分:6)

如果您确定,两个词典中的键名相同:

    clientlist = dict([(k, [clientList[k], recordlist[k]]) for k in clientList])

喜欢这里:

    >>> a = {1:1,2:2,3:3}
    >>> b = {1:11,2:12,3:13}
    >>> c = dict([(k,[a[k],b[k]]) for k in a])
    >>> c
    {1: [1, 11], 2: [2, 12], 3: [3, 13]}

答案 1 :(得分:1)

假设您需要与两个列表中的每个键对应的值列表,请尝试以此作为开头:

from pprint import pprint

clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]
clientList.extend(recordList)

outputList = {}

for rec in clientList:
    k = rec.keys()[0]
    v = rec.values()[0]
    if k in outputList:
        outputList[k].append(v)
    else:
        outputList[k] = [v,]

pprint(outputList)

它会产生这个:

{'client1': [['c1', 'f1'], {'rec_1': ['t1', 's1']}, {'rec_2': ['t2', 's2']}],
 'client2': [['c2', 'f2']]}

答案 2 :(得分:1)

这可行,但我不确定我理解您的数据结构规则。

# join all the dicts for better lookup and update
clientDict = {}
for d in clientList:
    for k, v in d.items():
        clientDict[k] = clientDict.get(k, []) + v

recordDict = {}
for d in recordList:
    for k, v in d.items():
        recordDict[k] = recordDict.get(k, []) + [v]

for k, v in recordDict.items():
    clientDict[k] = [clientDict[k]] + v

# I don't know why you need a list of one-key dicts but here it is
clientList = [dict([(k, v)]) for k, v in clientDict.items()]

使用您提供的样本数据,可以得到您想要的结果,希望它有所帮助。