第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何訪問嵌套在字典中的字典的值

如何訪問嵌套在字典中的字典的值

藍山帝景 2022-06-28 10:19:44
我需要編寫一個函數(shù),該函數(shù)接受一個字典,其鍵等于名稱,值是字典。嵌套在其中的字典的鍵等于任務,其值等于任務花費的小時數(shù)。我需要返回一個字典,其中任務作為鍵,它的值是一個字典,名稱作為鍵,它的值是小時。我不知道如何訪問嵌套字典中的值,因此嵌套字典中的值與鍵相同。這是我所擁有的: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}}但我現(xiàn)在得到的是:new_dict = {'task1': {'Ben': 'Ben', 'alex': 'alex'}, 'task2': {'alex': 'alex'}}
查看完整描述

3 回答

?
慕桂英546537

TA貢獻1848條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號