Is instance of dict the whole items or keys

Hi, forum,

Sorting a dict without .items() and the result does not contain the value parts of the key-values:

sorted(d,         key=lambda x: (x.a,    x.b))
sorted(d.items(), key=lambda x: (x[0].a, x[0].b))

Looping a dict has this distinct too:

for k    in d:         ... 
for k, v in d.items(): ...

But why printing a dict without .items() can contain the value parts?

print(d.items())  # print(dict(d.items()))

How are class ‘dict’ and class ‘dict_items’ related?


‘printing’ the dict involves converting it to a string representation, and the dict class provides its own method for doing that which includes both the keys and values.

Iterating over a dict does not work the same way as printing it.

1 Like

Printing an object and iterating over an object are completely unrelated operations. Printing an object results in these steps:

  • print() function asks the object to convert to a string;
  • which calls either the __str__ or __repr__ special method;
  • and then prints that string.

In the case of dicts, their __repr__ method uses both keys and values to give you the string display form.

Iterating is more complex, there are two different techniques used by the interpreter to decide whether an object can be iterated (the modern “iterator protocol” and the older “sequence protocol”). But the details don’t really matter.

Iterating over a dict gives you the keys only:

list(mydict) == list(mydict.keys())

If you want the values you have to use the items() or values() methods.

See the documentation for dict for more information about the keys, items and values methods.

1 Like