3

我有两个单独的 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']]}]

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

4

3 回答 3

7

当您确定时,两个字典中的键名相同:

    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]}
于 2012-05-16T21:13:03.300 回答
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()]

使用您提供的示例数据,这给出了您想要的结果,希望它有所帮助。

于 2012-05-16T21:32:02.027 回答
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']]}
于 2012-05-16T20:44:48.263 回答