The len function of dictionary views

Function Name:

len

Function Signature:

len(dictionary_view)

Overview:

  • The len() function when called with a dictionary view returns a dictionary object.
  • The len() function can be passed of any of the following types: dict_keys or dict_items or dict_values

Parameters:

 dictionary_view - An object of type dict_keys or dict_items or dict_values.

Return Value:

The number of keys present in the dictionary view.

Example 1 - Dictionary view of keys:

# Example Python program that gets the length
# of a dictionary view object

# Create an empty dictionary
cityVsTemperature = dict();

# Record the temeprature of various cities
cityVsTemperature["Vancouver"]     = 46;
cityVsTemperature["Toronto"]     = 46;
cityVsTemperature["Montreal"]     = 51;
cityVsTemperature["Calgary"]     = 25 ;
cityVsTemperature["Quebec"]     = 42;

# Get the view on the keys part of the dictionary
keysView = cityVsTemperature.keys();

# Print the key count
keyCount = len(keysView);
print("There are %d keys in the dictionary"%keyCount);

Output:

There are 5 keys in the dictionary

Example 2 - Dictionary view of values:

# Example Python program that gets
# the length of the dictionary view of type
# dict_values

# Create a Python dictionary
intervalVsFrequency = {"00-01":1045,
                       "01-02":1120,
                       "02-03":1200,
                       "03-04":1670,
                       "04-05":1500,
                       };

# Get a view on the values part of the dictionary
valuesView = intervalVsFrequency.values();

# Get the value count
valueCount = len(valuesView);
print(valueCount);

Output:

5

Example 3 - Dictionary view of items:

# Example Python program that gets the view of a dictionary items and prints its length

# Create a dictionary
bodiesVsGravity = {"Sun": "274 m/s²",
                   "Mercury": "3.7 m/s²",
                   "Venus": "8.87 m/s²",
                   "Earth": "9.807 m/s²",
                   "Mars": "3.711 m/s²",
                   "Jupiter": "24.79 m/s²",
                   "Saturn": "10.44 m/s²",
                   "Uranus": "8.87 m/s²",
                   "Neptune": "11.15 m/s²"};

# Get a dictionary view of type dict_items
bodiesVsGravity = bodiesVsGravity.items();

print("The dictionary view of items:")
print(bodiesVsGravity);
print(type(bodiesVsGravity));

print("Number of items/name-value pairs in the dictionary:");
print(len(bodiesVsGravity));

Output:

The dictionary view of items:
dict_items([('Sun', '274 m/s²'), ('Mercury', '3.7 m/s²'), ('Venus', '8.87 m/s²'), ('Earth', '9.807 m/s²'), ('Mars', '3.711 m/s²'), ('Jupiter', '24.79 m/s²'), ('Saturn', '10.44 m/s²'), ('Uranus', '8.87 m/s²'), ('Neptune', '11.15 m/s²')])
<class 'dict_items'>
Number of items/name-value pairs in the dictionary:
9

 


Copyright 2024 © pythontic.com