2010-08-06 55 views
9

名单借助词典的列表,如下列:如何合并字典

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'} 
] 

是什么将它们组合成字典以下列表中的最佳方式:

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 
] 

或者将它以更好地存储数据不同,如:

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

感谢您的帮助。

+0

我已经接受了亚当的答案,因为它不正是我需要。其他答案 - 建议我将数据重组为字典 - 工作正常,但对于我的项目,我宁愿不使用ID作为键。 – Chris 2010-08-06 09:48:52

回答

17

这里是一个可能的解决方案:

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') 

产地:

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

正如你所看到的,我用一本字典('合并')作为一个中间点。当然,您可以通过不同的方式存储数据来跳过这一步,但也取决于您对这些变量的其他用途。

一切顺利。

+0

完美。非常感谢。 – Chris 2010-08-06 09:47:17

+0

嘿亚当。我使用这种方法来完成相同的工作,但是我的字典和列表非常庞大。我想知道如果你知道更快的方法来做到这一点。谢谢。 – 2011-12-05 12:00:43

3

字典基本上是(键,值)对的列表。

你的情况

user_course_score可以仅仅是(COURSE_ID,得分)一本字典,而不是一个字典列表(你只是复杂也不必要)

类似的,当然可以只是一本字典的(COURSE_ID,名)

你到底建议是正确的做法:)

2

拉胡尔是正确的;字典列表不是正确的做法。像这样思考:字典是数据片之间的映射。你的最后一个例子courses是存储数据的正确方法。那么你可以做这样的事情来存储每用户数据:

courses = { 
    1456: 'History', 
    316: 'Science', 
    926: 'Geography' 
} # Note the lack of quotes 

test_scores = { 
    1456: { <user-id>: <score on History test> }, 
    316: { <user-id>: <score on History test> }, 
    926: { <user-id>: <score on History test> } 
} 
0

您也可以尝试:

[ 
    course.update(score) for course 
    in courses for score in user_course_score 
    if course['course_id'] == score['course_id'] 
] 

:)