Astudent
Astudent

Reputation: 196

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.

Upvotes: 0

Views: 306

Answers (2)

bigbounty
bigbounty

Reputation: 17358

You need to enclose the dictionary with {}

In [164]: mydictionary
Out[164]:
{'1': {'key': 'x', 'key2': 'b'},
 '2': {'key': 'y', 'key2': 'b'},
 '3': {'key': 'y', 'key2': 'a'},
 '4': {'key': 'x', 'key2': 'b'}}

In [165]: {i:mydictionary[i] for i in mydictionary if mydictionary[i]["key"] == "x"}
Out[165]: {'1': {'key': 'x', 'key2': 'b'}, '4': {'key': 'x', 'key2': 'b'}}

Upvotes: 1

L. Letovanec
L. Letovanec

Reputation: 615

something like this?

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

Upvotes: 1

Related Questions