除了字符串和整数之外的 Python 字典键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4348232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:20:28  来源:igfitidea点击:

Python dictionary keys besides strings and integers?

pythondictionary

提问by Pete

Anyone have some neat examples of dictionaries with some interesting keys (besides the canonical string or integer), and how you used these in your program?

任何人都有一些带有一些有趣键的字典示例(除了规范字符串或整数),以及您如何在程序中使用这些键?

I understand all we need for a key is something hashable, meaning it must be immutable and comparable (has an __eq__()or __cmp__()method).

我知道我们需要一个键是 something hashable,这意味着它必须是不可变的和可比较的(有一个__eq__()or__cmp__()方法)。

A related question is: how can I quickly and slickly define a new hashable?

一个相关的问题是:我怎样才能快速而巧妙地定义一个新的hashable

采纳答案by kindall

Let's go for something a bit more esoteric. Suppose you wanted to execute a list of functions and store the result of each. For each function that raised an exception, you want to record the exception, and you also want to keep a count of how many times each kind of exception is raised. Functions and exceptions can be used as dictkeys, so this is easy:

让我们做一些更深奥的事情。假设您想执行一个函数列表并存储每个函数的结果。对于每个引发异常的函数,您都希望记录异常,并且还想记录每种异常引发的次数。函数和异常可以用作dict键,所以这很容易:

funclist = [foo, bar, baz, quux]

results    = {}
badfuncs   = {}
errorcount = {}

for f in funclist:
    try:
        results[f] = f()
    except Exception as e:
        badfuncs[f]   = e
        errorcount[type(e)] = errorcount[type(e)] + 1 if type(e) in errorcount else 1

Now you can do if foo in badfuncsto test whether that function raised an exception (or if foo in resultsto see if it ran properly), if ValueError in errorcountto see if any function raised ValueError, and so on.

现在您可以if foo in badfuncs测试该函数是否引发异常(或if foo in results查看它是否正常运行),if ValueError in errorcount查看是否有任何函数引发ValueError,等等。

回答by patrickmdnet

You can use a tuple as a key, for example if you want to create a multi-column index. Here's a simple example:

您可以使用元组作为键,例如,如果您想创建多列索引。这是一个简单的例子:

>>> index = {("John", "Smith", "1972/01/01"): 123, ("Bob", "Smith", "1972/01/02"): 124}
>>> index
{('Bob', 'Smith', '1972/01/02'): 124, ('John', 'Smith', '1972/01/01'): 123}
>>> index.keys()
[('Bob', 'Smith', '1972/01/02'), ('John', 'Smith', '1972/01/01')]
>>> index['John', 'Smith', '1972/01/01']
123

For an example of how to use a dict as a key (a hashable dict) see this answer: Python hashable dicts

有关如何使用 dict 作为键(可散列的 dict)的示例,请参阅此答案: Python hashable dicts

回答by eldarerathis

Note that I've never really used this, but I've always thought using tuples as keys could let you do some interesting things. I would find it a convenient way to map grid coordinates, for example. You can think of this like a grid on a video game (maybe some kind of tactics game like Fire Emblem):

请注意,我从未真正使用过它,但我一直认为使用元组作为键可以让您做一些有趣的事情。例如,我会发现这是一种映射网格坐标的便捷方法。你可以把它想象成一个电子游戏中的网格(可能是某种战术游戏,比如Fire Emblem):

>>> Terrain = { (1,3):"Forest", (1,5):"Water", (3,4):"Land" }
>>> print Terrain
{(1, 5): 'Water', (1, 3): 'Forest', (3, 4): 'Land'}
>>> print Terrain[(1,3)]
Forest
>>> print Terrain[(1,5)]
Water
>>> x = 3
>>> y = 4
>>> print Terrain[(x,y)]
Land

Something like that.

类似的东西。

Edit: As Mark Rushakof pointed out in the comments, I'm basically intending this to be a sparse array.

编辑:正如 Mark Rushakof 在评论中指出的那样,我基本上打算将其作为一个sparse array

回答by Sven Marnach

You left out the probably most important method for an object to be hashable: __hash__().

您遗漏了对象可散列的可能最重要的方法:__hash__()

The shortest implementation of your own hashable type is this:

您自己的可散列类型的最短实现是这样的:

class A(object):
    pass

Now you can use instances of Aas dictionary keys:

现在你可以使用实例A作为字典键:

d = {}
a = A()
b = A()
d[a] = 7
d[b] = 8

This is because user-defined classes are hashable by default, and their hash value is their id -- so they will only compare equal if they are the same object.

这是因为用户定义的类在默认情况下是可散列的,它们的散列值是它们的 id——所以如果它们是相同的对象,它们只会比较相等。

Note that instances of Aare by no means immutable, and they can be used as dictionary keys nevertheless. The statement that dictionary keys must be immutable only holds for the built-in types.

请注意, 的实例A绝不是不可变的,但它们仍然可以用作字典键。字典键必须是不可变的声明仅适用于内置类型。

回答by omatai

I have no idea why you'd want to do it (and preferably, please don'tdo it)... but alongside strings and integers, you can also use both simultaneously. That is, as a beginner, I found it both powerful and surprising that:

我不知道您为什么要这样做(最好要这样做)……但是除了字符串和整数之外,您还可以同时使用两者。也就是说,作为初学者,我发现它既强大又令人惊讶:

foo = { 1:'this', 2:'that', 'more':'other', 'less':'etc' }

is an entirely valid dictionary, which provides access to foo[2]as easily as it does to foo['more'].

是一个完全有效的字典,它提供foo[2]foo['more'].