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

2024-09-28 12:13:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要写一个函数,它接受一个字典,它的键等于一个名称,值就是字典。嵌套在其中的字典的键等于一个任务,其值等于该任务所用的小时数。我需要返回一个dictionary,其中task是键,value是值,name是键,value是小时。你知道吗

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

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

Tags: 函数in名称newfordictionary字典value
3条回答

尽管上面的答案是正确的,但为了更好的理解,我还是将这张幻灯片滑动一下:)

from collections import defaultdict

def 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_dict

a = 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()来获取值。你知道吗

这是我的工作

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_dict

print(sprintLog({'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}}))

相关问题 更多 >

    热门问题