Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a mapping object, according to dict type?

The documentation lists 3 ways for creating a dict instance:

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

What exactly is a mapping here? What's the minimal interface required for dict(mapping) to work?

like image 362
wim Avatar asked Nov 17 '16 23:11

wim


People also ask

What is mapping type dict in Python?

A mapping type is a data type comprised of a collection of keys and associated values. Python's only built-in mapping type is the dictionary. Dictionaries implement the associative array abstract data type.

What is mapping object in Python?

A mapping object maps values of one type (the key type) to arbitrary objects. Mappings are mutable objects. There is currently only one mapping type, the dictionary . A dictionary's keys are almost arbitrary values.

Is dictionary a mapping?

In mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key “maps to” a value. As an example, we'll build a dictionary that maps from English to Spanish words, so the keys and the values are all strings.


1 Answers

From the source code for CPython, this comment:

/* We accept for the argument either a concrete dictionary object,
 * or an abstract "mapping" object.  For the former, we can do
 * things quite efficiently.  For the latter, we only require that
 * PyMapping_Keys() and PyObject_GetItem() be supported.
 */

So, "the minimal interface required for dict(mapping) to work" appears to be .keys() and .__getitem__().

Example program:

class M:
    def keys(self):
        return [1,2,3]
    def __getitem__(self, x):
        return x*2

m = M()

d = dict(m)

assert d == {1:2, 2:4, 3:6}
like image 148
Robᵩ Avatar answered Sep 21 '22 17:09

Robᵩ