python – dict_item

Reading Time: < 1 minute

Last updated: 7/1/2024

Dictionaries are used to store items in key:value pairs.

A common way to learn more about a class is to examine it. Let’s use the dir function to iterate through the properties and methods of the “dict_item”.

>>> example_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> x = example_dict.items()
>>> print(type(x))
<class 'dict_items'>
>>> print(dir(x))
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'isdisjoint', 'mapping']

As of python 2.7 dictionary objects are ordered.

We can find the length of a dictionary; or another way of putting this is the number of items in a dictionary.

print(len(example_dict))

We can loop through the elements of a dictionary.

for x in example_dict:
  print(x)

References:
https://www.w3schools.com/python/python_dictionaries.asp

This entry was posted in Python. Bookmark the permalink.