Larry.Fish
Larry.Fish

Reputation: 123

How to access the values of a dictionary that is nested inside a dictionary

I need to write a function that takes a dictionary with its keys equal to a name and the values are dictionaries. The dictionary that is nested inside has the key equal to a task and its value equal to the number of hours that task takes. I need to return a dictionary with the task as the key and its value a dictionary with the name as the key and its value the hours.

I can't figure out how to access the values inside the nested dictionary so the values in the nested dictionary are just the same as the keys. Here is what I have:

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

If I pass in a dictionary such as:

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

I'm expecting to get a dictionary such as:

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

But what I am getting at the moment is:

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

Upvotes: 1

Views: 100

Answers (3)

P.hunter
P.hunter

Reputation: 1365

Even though the above answers with list comprehension are correct, I'll just slide this one for better understanding :)

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)

Upvotes: 1

Arsham Mohammadi
Arsham Mohammadi

Reputation: 401

this is work for me

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

Upvotes: 1

Kostas Charitidis
Kostas Charitidis

Reputation: 3113

I think that's what you're looking for:

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

You need to use sprnt.items() instead of sprnt.keys() so to get the values too.

Upvotes: 0

Related Questions