Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "dict-like" mean in Python?

Occasionally people refer to "X-like" objects in Python. Example:

data_iter_maker – A zero-argument callable which returns an iterator over dict-like data objects.

Does "dict-like" have a precise definition, and if so, what is it? Would it be an object x that can be indexed like a dictionary can: x[a], where a is a hashable? In that case, a namedtuple might not be considered dict-like, since you can't index using an expression like x['a'] (last I checked you have to write x.a). But on the other hand, namedtuples are functionally so similar to dicts that I'm not sure what to think.

Cynically, I'm tempted to guess that "dict-like" means "an object similar enough to dict that my code will produce the same answer as if you had submitted a semantically equivalent dict object". In other words, "run the function and find out for yourself if your argument is dict-like!"

More generally, is an X-like object one which implements the same interface as X?

like image 490
Paul Avatar asked Nov 21 '15 16:11

Paul


People also ask

What does dict in Python mean?

Python dict() Function The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.

Are Python dictionaries like objects?

Python provides another composite data type called a dictionary, which is similar to a list in that it is a collection of objects.

What does a dictionary look like in Python?

A dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. Dictionaries are written with curly brackets ({}), including key-value pairs separated by commas (,). A colon (:) separates each key from its value.

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.


1 Answers

Python uses 'duck-typing':

“If it looks like a duck and quacks like a duck, it must be a duck.”

Or perhaps, "If it looks like a duck and quacks like a duck, it is sufficiently close to a duck to treat it like one." Obviously the first sounds better. This is closely related to the python doctrine of "Easier to Ask for Forgiveness than to ask for Permission".

A dict-like object is one which implements (or emulates) the dictionary interface. The same concept often comes up for iterables, and often in numpy for 'array-like' (or 'array_like') objects.

like image 70
DilithiumMatrix Avatar answered Oct 01 '22 11:10

DilithiumMatrix