shelbydz
shelbydz

Reputation: 533

Python nested dictionary comprehension returns empty dictionaries

I'm using dictionary comprehension to pull out a nested value. I have the following code (as a sample):

d = {1: 'a', 2: 'b', 3: 'c'}
e = {4: 'd', 5: 'e', 6: 'f'}
f = {7: 'g', 8: 'h', 9: 'i'}

# stick them together into another dict
data_dict = {'one': d, 'two': e, 'three': f}
#say we're looking for the key 8

output = {outer_key: {inner_key: inner_value for inner_key, inner_value in outer_value.items() if inner_key == 8} for outer_key, outer_value in data_dict.items()}
output = {'one': {}, 'three': {8: 'h'}, 'two': {}}

what do I need to do to get JUST 'three' and its value? I don't want to return empty matches.

thx

Upvotes: 3

Views: 1237

Answers (2)

dstromberg
dstromberg

Reputation: 7177

A comprehension of 162+ lines is too big. Here's the traditional way:

#!/usr/local/cpython-3.3/bin/python

import pprint

d = {1: 'a', 2: 'b', 3: 'c'}
e = {4: 'd', 5: 'e', 6: 'f'}
f = {7: 'g', 8: 'h', 9: 'i'}

# stick them together into another dict
data_dict = {'one': d, 'two': e, 'three': f}
#say we're looking for the key 8

def just_8(dict_):
    outer_result = {}
    for outer_key, inner_dict in dict_.items():
        inner_result = {}
        if 8 in inner_dict:
            inner_result[8] = inner_dict[8]
        if inner_result:
            outer_result[outer_key] = inner_result
    return outer_result

output = {outer_key: {inner_key: inner_value for inner_key, inner_value in outer_value.items() if inner_key == 8} for outer_key, outer_value in data_dict.items()}
pprint.pprint(output)

output_just_8 = just_8(data_dict)
pprint.pprint(output_just_8)

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250981

Something like this:

>>> {k: {8: v[8]} for k, v in data_dict.items() if 8 in v}
{'three': {8: 'h'}}

Upvotes: 5

Related Questions