Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典外的列表中获取键值_Python_Dictionary - Fatal编程技术网

Python 从字典外的列表中获取键值

Python 从字典外的列表中获取键值,python,dictionary,Python,Dictionary,我试图计算字典中每个键的“分数”。键值的值位于不同的列表中。简化示例: 我有: 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] 您可以使用dict理解创建它: Key_values = {'a': 1, 'b': 2, 'c': 3,

我试图计算字典中每个键的“分数”。键值的值位于不同的列表中。简化示例:

我有:

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]

您可以使用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}
试试这个:(更新了有问题的语法。键值对被括在花括号内。)

试试这个:

>>键值={“a”:1,“b”:2,“c”:3,“d”:4}
>>>My_dict={“player1”:[“a”、“d”、“c”],“player2”:[“b”、“a”、“d”]}
>>>得分={k:sum(v中v的Key_values.get(v_el,0))k,v在My_dict.items()中的得分}
>>>得分
{'player1':8'player2':7}
试试这个:

   score = {}
    key_values  = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    my_dict = {'player1': ['a', 'c', 'd'], 'player2': ['b', 'a', 'd']}
    scr = 0
    for i in my_dict.keys(): # to get all keys from my_dict
      for j in my_dict[i]: # iterate the value list for key.
        scr += key_values[j]
      score[i] = scr
      scr = 0

    print(score)

你可以用适当的
dict
方法和map来完成,应该是已经发布的方法中速度最快的

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

new_dict = {key:sum(map(Key_values.get,My_dict[key])) for key in My_dict}
print(new_dict)
输出:

{'player1': 8, 'player2': 7}

如果这让事情变得更简单,请在您的问题中粘贴有效的Python代码。例如,您的引号不是普通引号,Python将其视为无效字符。
{'player1': 8, 'player2': 7}