On Tue, Jul 29, 2014 at 06:12:16PM -0500, Ron Adam wrote on the similarity of lists and dicts: [...]
Well, here is how they currently compare.
set(dir(dict)).intersection(set(dir(list))) {'copy', '__hash__', '__format__', '__sizeof__', '__ge__', '__delitem__', '__getitem__', '__dir__', 'pop', '__gt__', '__repr__', '__init__', '__subclasshook__', '__eq__', 'clear', '__len__', '__str__', '__le__', '__new__', '__reduce_ex__', '__doc__', '__getattribute__', '__ne__', '__reduce__', '__contains__', '__delattr__', '__class__', '__lt__', '__setattr__', '__setitem__', '__iter__'}
Now strip out the methods which are common to pretty much all objects, in other words just look at the ones which are common to mapping and sequence APIs but not to objects in general: {'copy', '__ge__', '__delitem__', '__getitem__', 'pop', '__gt__', 'clear', '__len__', '__le__', '__contains__', '__lt__', '__setitem__', '__iter__'} And now look a little more closely: - although dicts and lists both support order comparisons like > and <, you cannot compare a dict to a list in Python 3; - although dicts and lists both support a pop method, their signatures are different; x.pop() will fail if x is a dict, and x.pop(k, d) will fail if x is a list; - although both support membership testing "a in x", what is being tested is rather different; if x is a dict, then a must be a key, but the analog of keys for lists is the index, not the value. So the similarities between list and dict are: * both have a length * both are iterable * both support subscripting operations x[i] * although dicts don't support slicing x[i:j:k] * both support a copy() method * both support a clear() method That's not a really big set of operations in common, and they're rather general. The real test is, under what practical circumstances would you expect to freely substitute a list for a dict or visa versa, and what could you do with that object when you received it? For me, the only answer that comes readily to mind is that the dict constructor accepts either another dict or a list of (key,item) pairs. [...]
They do have quite a lot in common already. The usefulness of different types having the same methods is that external code can be less specific to the objects they handle.
I don't think that it is reasonable to treat dicts and lists as having a lot in common. They have a little in common, by virtue of both being containers, but then a string bag and a 40ft steel shipping container are both containers too, so that doesn't imply much similarity :-) It seems to me that outside of utterly generic operations like iteration, conversion to string and so on, lists do not quack like dicts, and dicts do not swim like lists, in any significant sense. -- Steven