如何访问嵌套在字典中的字典的值

我需要编写一个函数,该函数接受一个字典,其键等于名称,值是字典。嵌套在其中的字典的键等于任务,其值等于任务花费的小时数。我需要返回一个字典,其中任务作为键,它的值是一个字典,名称作为键,它的值是小时。

我不知道如何访问嵌套字典中的值,因此嵌套字典中的值与键相同。这是我所拥有的:

def sprintLog(sprnt):
    new_dict = {}
    new_dict = {x: {y: y for y in sprnt.keys() if x in sprnt[y]} for l in sprnt.values() for x in l}
        return new_dict

如果我传入字典,例如:

d = {'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}}

我期待得到一本字典,例如:

new_dict = {'task1': {'Ben': 5, 'alex': 10}, 'task2': {'alex': 4}}

但我现在得到的是:

new_dict = {'task1': {'Ben': 'Ben', 'alex': 'alex'}, 'task2': {'alex': 'alex'}}


蓝山帝景
浏览 197回答 3
3回答

慕桂英546537

这对我有用def sprintLog(sprnt):    new_dict = {}    new_dict = {x: {y: sprnt[y][x] for y in sprnt.keys() if x in sprnt[y]} for l in sprnt.values() for x in l}    return new_dictprint(sprintLog({'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}}))

猛跑小猪

即使上面的列表理解答案是正确的,我还是会滑动这个答案以便更好地理解:)from collections import defaultdictdef sprintLog(sprnt): # d = {'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}}    new_dict = defaultdict(dict)    for parent in sprnt.keys():        for sub_parent in sprnt[parent].keys():           new_dict[sub_parent][parent] = sprnt[parent][sub_parent]    return new_dicta = sprintLog({'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}})print(a)

慕森卡

我想这就是你要找的:d = {'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}}def sprintLog(sprnt):    return {x: {y: f[x] for y,f in sprnt.items() if x in sprnt[y]} for l in sprnt.values() for x in l}print(sprintLog(d))您也需要使用sprnt.items()而不是sprnt.keys()so 来获取值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python