Python:从dict中,如何将对象检索为关键

时间:2017-07-23 21:10:51

标签: python key-value

如果我有多个[key]的字典,如何使用class Obj(): def __init__(self, value): self.value = value dct = {Obj(foo):foo_value, Obj(bar):bar_value} #How to do something like #>>> dct[foo] #foo_value 检索某个对象?

例如

class Obj():
    def __init__(self, name):
        self.name = name
    def __hash__(self):
        return hash(tuple(sorted(self.__dict__.items())))
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__
        else:
            return False
    def __repr__(self):
        return str(self.name)

dct = {Obj('item1'):1, Obj('item2'):2}

print(dct.keys())
dct['item1']

假设foo_value不能作为Obj的属性被赋值。

到目前为止,这是我得到的(抽象的)

dict_keys([item1, item2])
Traceback (most recent call last):
    File "C:\Users\ivan\Desktop\multi_e.py", line 197, in <module>
     dct['item1']
KeyError: 'item1'

输出

ionic plugin add cordova-plugin-network-information

npm install --save @ionic-native/network

4 个答案:

答案 0 :(得分:2)

这不起作用,因为键不是字符串,但它们是Obj类型的对象。即使所有对象都持有该字符串 你可以做到这一点。将变量存储为对象的引用作为键

x = Obj("item1")
y = Obj("item2")
dct= {x:1, y:2}

要检索你需要做的事情:

>>> dct[x]
1

答案 1 :(得分:2)

使用==12768== Syscall param msg->desc.port.name points to uninitialised byte(s) ==12768== at 0x10049434A: mach_msg_trap (in /usr/lib/system/libsystem_kernel.dylib) ==12768== by 0x100493796: mach_msg (in /usr/lib/system/libsystem_kernel.dylib) ==12768== by 0x10048D485: task_set_special_port (in /usr/lib/system/libsystem_kernel.dylib) ==12768== by 0x10062910E: _os_trace_create_debug_control_port (in /usr/lib/system/libsystem_trace.dylib) ==12768== by 0x100629458: _libtrace_init (in /usr/lib/system/libsystem_trace.dylib) ==12768== by 0x1001599DF: libSystem_initializer (in /usr/lib/libSystem.B.dylib) ==12768== by 0x100017A1A: ImageLoaderMachO::doModInitFunctions(ImageLoader::LinkContext const&) (in /usr/lib/dyld) ==12768== by 0x100017C1D: ImageLoaderMachO::doInitialization(ImageLoader::LinkContext const&) (in /usr/lib/dyld) ==12768== by 0x1000134A9: ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, char const*, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) (in /usr/lib/dyld) ==12768== by 0x100013440: ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, char const*, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) (in /usr/lib/dyld) ==12768== by 0x100012523: ImageLoader::processInitializers(ImageLoader::LinkContext const&, unsigned int, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) (in /usr/lib/dyld) ==12768== by 0x1000125B8: ImageLoader::runInitializers(ImageLoader::LinkContext const&, ImageLoader::InitializerTimingList&) (in /usr/lib/dyld) ==12768== Address 0x10488ac6c is on thread 1's stack ==12768== in frame #2, created by task_set_special_port (???:) ==12768== Uninitialised value was created by a stack allocation ==12768== at 0x1006290A6: _os_trace_create_debug_control_port (in /usr/lib/system/libsystem_trace.dylib) 的自定义实现怎么样?

dict

答案 2 :(得分:1)

您可以使用自定义__getitem____setitem__推出自己的dict子类,而真的不需要__hash__方法{ {1}}之后的课程,只需Obj即可。

__init__

<强>演示:

class Obj:
    def __init__(self, value):
        self.name = value

class MyDict(dict):
    def __setitem__(self, key, value):
        if isinstance(key, Obj):
            dict.__setitem__(self, key.name, value)
        else:
            dict.__setitem__(self, key, value)

    def __getitem__(self, key):
        if isinstance(key, Obj):
            return dict.__getitem__(self, key.name)
        return dict.__getitem__(self, key)

答案 3 :(得分:1)

我尝试了一点时间,但我想我得到了你想要的东西,看:

  

感谢@ user2357112

    public static OpenIdConnectOptions CreateAzureAdOptions(X509Certificate2 certificate2, IConfiguration configuration)
    {
        return new OpenIdConnectOptions
        {
            DisplayName = "Azure Active Directory",
            AuthenticationScheme = "Azure",
            ClientId = configuration["OpenId:AzureAD:AppId"],
            Authority = string.Format(CultureInfo.InvariantCulture, "https://login.windows.net/{0}", configuration["OpenId:AzureAD:Instance"]),
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false
            },
            // https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-token-and-claims
            Scope = {"openid", "email", "roles", "groups"},
            Events = new OpenIdConnectEvents
            {
                OnRemoteFailure = context => HandleRemoteFailure(context)
            },
            SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme
        };
    }

    private static Task HandleRemoteFailure(FailureContext context)
    {
        Log.Error(context.Failure, "Azure AD Remote Failure");
        context.Response.Redirect("/accessdenied");
        context.HandleResponse();
        return Task.FromResult(0);
    }
  

5   [&#39; item1&#39;,&#39; item2&#39;]

     

1