如何组合两个词典序列的数据

时间:2015-09-23 13:11:35

标签: python dictionary lambda sequences

我有两个清单:

list1 = [{'tag':'XXX', 'key1':'a'}, {'tag':'YYY', 'key1':'a'}]

list2 = [{'tag':'XXX', 'key1':'c'}, {'tag':'ZZZ', 'key1':'d'}]

我需要建立一个新列表:

 comblist = [{'tag':'XXX', 'key1':'a'}, {'tag':'YYY', 'key1':'a'}, {'tag':'ZZZ', 'key1':'d'}]

我需要将list2中的元素添加到list1,但只有list1中键'tag'的值中不存在键'tag'的值。

3 个答案:

答案 0 :(得分:3)

您可以先从list1创建一组标记值,然后使用理解通过列表2中包含新标记的词典来扩展list1:

>>> list1 = [{'tag':'XXX', 'key1':'a'}, {'tag':'YYY', 'key1':'a'}]
>>> list2 = [{'tag':'XXX', 'key1':'c'}, {'tag':'ZZZ', 'key1':'d'}]
>>> tags = set(d['tag'] for d in list1)
>>> list1.extend(d for d in list2 if not d['tag'] in tags)
>>> list1
[{'key1': 'a', 'tag': 'XXX'}, {'key1': 'a', 'tag': 'YYY'}, {'key1': 'd', 'tag': 'ZZZ'}]

答案 1 :(得分:0)

使用字典的更新方法可以更简单:

dict1 = dict((x['tag'], x['key1']) for x in list1)
dict2 = dict((x['tag'], x['key1']) for x in list2)

result = dict2.copy()
result.update(dict1)

result = [{'tag': key, 'key1': value} for key, value in result.iteritems()]

答案 2 :(得分:0)

所以我建立了功能:

def add(seq1, seq2, key=None):
seen = set()
#add values from seq1 for selected key (or keys) to seen.
for item in seq1:
    seen.add(key(item))
# Check if value(s) for selected key(s) is in seen.   
for item in seq2:
    # if statemant added for support two types of sequences lists end dicts
    val = item if key is None else key(item)
    if val not in seen:
        # Add selected element from seq2 to seq1 and value of key to seen
        seq1.append(item)
        seen.add(val)
return seq1

并称之为:

comblist = list(add(list1, list2, key=lambda d: d['tag']))

效果很好。 函数适用于不同类型的数据结构和属性。 我不是亲,我很好奇。有没有更简单或更快的方式? 我的列表包含超过1500个字典,每个字典有15个键值对。