Search code examples
python-3.xkey-valuedictionary-comprehension

Selecting objects with specific key:value pair from dictionary


I want to pick all the objects that have a specific key:value pair in a dictionary.

For example: if I wanted the pairs "key":"x" from the following dictionary:

mydictionary =
    "1" : {
        "key" : "x",
        "key2" : "b",
    },
    "2" : {
        "key" : "y",
        "key2" : "b",
    },
    "3" : {
        "key" : "y",
        "key2" : "a",
    },
    "4" : {
        "key" : "x",
        "key2" : "b",
    }

The output would be objects "1" and "4".

This is a likely duplicate, but I couldn't find a similar problem despite searching.


Solution

  • something like this?

    [k for k, v in mydictionary.items() if v['key'] == 'x']