Python Forum

Full Version: Dictionary filtering and intermediate keys
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have the below code, which is working fine, although I understand it is not the most efficient from a resource aspect.

I believe it is possible to implement it more elegantly with dictionary comprehension but I can't figure out how.


d ={'subkey':{'item1':{'num':'one','word':'alfa'},'item2':{'num':'two','word':'bravo'},'item3':{'num':'three','word':'charlie'} }}
newdict = {}

for key in d:
    for subkey in d[key]:
        if "l" in d[key][subkey]['word']:
            newdict[subkey] = d[key][subkey]
print(newdict)
Could someone help?

Thanks,

Gilles95
This is just as much code, but another way to do it
d = {'subkey': {'item1': {'num': 'one', 'word': 'alfa'}, 'item2': {'num': 'two', 'word': 'bravo'},
                'item3': {'num': 'three', 'word': 'charlie'}}}

newdict = {}

for key, value in d.items():
    if isinstance(value, dict):
        for key, value in value.items():
            newdict[key] = value
print(newdict)
your code should look like this with dictionary comprehension....did this in python 2.7 just in case error occured
newdict={ subkey:d[key][subkey] for key in d for subkey in d[key] if "l" in d[key][subkey]['word']}
we can left out for key in d loop since d has only 1 item, code reduced into
newdict={key:d['subkey'][key] for key in d['subkey'] if 'l'in d['subkey'][key]['word']}
Thanks a lot! This resolved my query.