Home > Mobile >  Nested Dictionaries - Grab top-level keys where specified field in sub-dictionaries satisfies criter
Nested Dictionaries - Grab top-level keys where specified field in sub-dictionaries satisfies criter

Time:06-25

This is a simple question but one which I'm having trouble finding an answer to. Data example:

nested = {
    "Moli": {
        "Buy": 75,
        "Sell": 53,
        "Quantity": 300,
        "TF": True},
    "Anna": {
        "Buy": 55,
        "Sell": 83,
        "Quantity": 154,
        "TF": False},
    "Bob": {
        "Buy": 25,
        "Sell": 33,
        "Quantity": 100,
        "TF": False},
    "Annie": {
        "Buy": 74,
        "Sell": 83,
        "Quantity": 96,
        "TF": True}
}

I've already got:

subset = [d for d in nested.values() if d['TF'] == False]

This gives me a new nested dictionary, with two sub-dictionaries instead of four. But what if I just want it to output an object list of the names. I.e. ["Anna" , "Bob"]. How do I select the keys instead of the values?

CodePudding user response:

You were close, you can loop over keys instead of values.

nested = {
    "Moli": {"Buy": 75, "Sell": 53, "Quantity": 300, "TF": True},
    "Anna": {"Buy": 55, "Sell": 83, "Quantity": 154, "TF": False},
    "Bob": {"Buy": 25, "Sell": 33, "Quantity": 100, "TF": False},
    "Annie": {"Buy": 74, "Sell": 83, "Quantity": 96, "TF": True},
}

filtered = [x for x in nested.keys() if not nested[x]["TF"]]
print(filtered)

CodePudding user response:

Use list comprehension while iterating over tuples of dictionary items: keys and values. You might also be able to use a shorter not v['TF'] if "falsy" is a good enough test for you:

subset = [k for k, v in nested.items() if not v['TF']]
print(subset)
# ['Anna', 'Bob']
  • Related