首页 > 解决方案 > 从字典外的列表中获取键值

问题描述

我正在尝试为字典中的每个键计算一个“分数”。键值的值在不同的列表中。简化示例:

我有:

Key_values = ['a': 1, 'b': 2, 'c': 3, 'd': 4]
My_dict = {'player1': ['a', 'd', 'c'], 'player2': ['b', 'a', 'd']}

我想:

Scores = ['player1': 8, 'player2': 7]

标签: pythondictionary

解决方案


您可以使用 dict 理解创建它:

Key_values = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
My_dict = {'player1': ['a', 'd', 'c'], 'player2': ['b', 'a', 'd']}

scores = {player: sum(Key_values[mark] for mark in marks) for player, marks in My_dict.items()}

print(scores)
# {'player1': 8, 'player2': 7}

推荐阅读