Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge lists of dictionaries

Tags:

python

With lists of dictionaries such as the following:

user_course_score = [
    {'course_id': 1456, 'score': 56}, 
    {'course_id': 316, 'score': 71}
]
courses = [
    {'course_id': 1456, 'name': 'History'}, 
    {'course_id': 316, 'name': 'Science'}, 
    {'course_id': 926, 'name': 'Geography'}
]

What is the best way to combine them into the following list of dictionaries:

user_course_information = [
    {'course_id': 1456, 'score': 56, 'name': 'History'}, 
    {'course_id': 316, 'score': 71, 'name': 'Science'}, 
    {'course_id': 926, 'name': 'Geography'} # Note: the student did not take this test
]

Or would it be better to store the data differently, such as:

courses = {
    '1456': 'History',
    '316': 'Science',
    '926': 'Geography'
}

Thanks for your help.

like image 686
Chris Avatar asked Aug 06 '10 07:08

Chris


People also ask

How do I concatenate a list of dictionaries in Python?

To merge multiple dictionaries, the most Pythonic way is to use dictionary comprehension {k:v for x in l for k,v in x. items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.

How do you merge lists in Python?

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.


1 Answers

Here's a possible solution:

def merge_lists(l1, l2, key):
    merged = {}
    for item in l1+l2:
        if item[key] in merged:
            merged[item[key]].update(item)
        else:
            merged[item[key]] = item
    return merged.values()

courses = merge_lists(user_course_score, courses, 'course_id')

Produces:

[{'course_id': 1456, 'name': 'History', 'score': 56},
 {'course_id': 316, 'name': 'Science', 'score': 71},
 {'course_id': 926, 'name': 'Geography'}]

As you can see, I used a dictionary ('merged') as a halfway point. Of course, you can skip a step by storing your data differently, but it depends also on the other uses you may have for those variables.

All the best.

like image 64
Adam Avatar answered Sep 23 '22 18:09

Adam