为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蓝山帝景 2022-06-28 10:19:44
我需要编写一个函数,该函数接受一个字典,其键等于名称,值是字典。嵌套在其中的字典的键等于任务,其值等于任务花费的小时数。我需要返回一个字典,其中任务作为键,它的值是一个字典,名称作为键,它的值是小时。我不知道如何访问嵌套字典中的值,因此嵌套字典中的值与键相同。这是我所拥有的: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'}}
查看完整描述

3 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

这对我有用


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


查看完整回答
反对 回复 2022-06-28
?
猛跑小猪

TA贡献1858条经验 获得超8个赞

即使上面的列表理解答案是正确的,我还是会滑动这个答案以便更好地理解:)


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)


查看完整回答
反对 回复 2022-06-28
?
慕森卡

TA贡献1806条经验 获得超8个赞

我想这就是你要找的:


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 来获取值。


查看完整回答
反对 回复 2022-06-28
  • 3 回答
  • 0 关注
  • 196 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号