Python Forum
Dictionary filtering and intermediate keys
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary filtering and intermediate keys
#1
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
Reply
#2
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)
Reply
#3
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']}
swallow osama bin laden
Reply
#4
Thanks a lot! This resolved my query.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  filtering a list of dictionary as per given criteria jss 5 655 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Adding keys and values to a dictionary giladal 3 2,464 Nov-19-2020, 04:58 PM
Last Post: deanhystad
  two conditionals with intermediate code Skaperen 5 2,756 Jul-12-2020, 07:18 PM
Last Post: Skaperen
  access dictionary with keys from another and write values to list redminote4dd 6 3,219 Jun-03-2020, 05:20 PM
Last Post: DeaD_EyE
  Drop Keys From Dictionary donnertrud 8 3,649 May-30-2020, 11:39 AM
Last Post: DeaD_EyE
  Problem adding keys/values to dictionary where keynames = "property" and "value" jasonashaw 1 2,033 Dec-17-2019, 08:00 PM
Last Post: jasonashaw
  Checking if the combination of two keys is in a dictionary? mrsenorchuck 6 3,868 Dec-04-2019, 10:35 AM
Last Post: mrsenorchuck
  Retrieving dictionary keys within with another dictionay bazcurtis 8 2,802 Oct-29-2019, 10:06 PM
Last Post: bazcurtis
  intermediate book recommendation please? jameson984 1 2,011 Jul-15-2019, 03:21 AM
Last Post: metulburr
  json.dumps to keep dictionary keys batchenr 1 2,007 May-14-2019, 11:17 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020