Skip to content

How to test if a key exists in py::dict #1340

Closed

Description

@xush6528

I want to do something similar to

if (kwargs["switch"] != py::none()) {
    switch = switch["shuffle"];
}

Activity

  1. jagerman commented on Mar 29, 2018

    @jagerman
    Member

    You can check for existence of the key with obj.contains:

    if (kwargs.contains("switch")) {
        // ...
    }

    and for the value equaling none with obj.is_none():

    if (!kwargs["switch"].is_none()) {
        // ...
    }

    But note that, like Python, key existence and value equaling None are different: it is possible for a dictionary to contain the key "switch" with a value of None, which is different than the dictionary not containing the key. So you may actually want:

    if (kwargs.contains("switch") && !kwargs["switch"].is_none()) {
        // ...
    }

    It's also possible to do a None check using !val.is(py::none()) rather than !val.is_none(), but it's slightly more verbose, and slightly less efficient.

  2. ecolss commented on May 30, 2018

    @ecolss

    @jagerman what if I want the key to be integer, not string, looks like it cannot compile at all

  3. cielavenir commented on Jan 30, 2024

    @cielavenir
    Contributor

    @ecolss @jagerman it should be addressed by #4004 . I don't know why it is taking time.

  4. cielavenir commented on Jan 30, 2024

    @cielavenir
    Contributor

    though you can use dic[py::cast(num)]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions