Dictionary View Objects In Python

Introduction:

  • A view on a dictionary object, acts as a read-only reference to certain parts of the dictionary. These parts are keys, values and the items(key+value i,e., the name value pairs).
  • Dictionary views allows operations like membership test, iteration, getting the length of the dictionary(number of keys==number of items==dictionary length) and getting the view members in reverse order.

Dictionary view objects in Python

  1. dict_keys: Obtained by calling the keys() method.
  2. dict_values: Obtained by calling the values() method
  3. dict_items: Obtained by calling the items() method

Example:

# Example Python program that creates a dictionary view on the keys of
# a dict instance

# A dictionary of cities and their co-ordinates
cityVsLatLong = {"Washington, D.C.":("38.9101°N", "77.0147°W"),
                 "New York City":("40.712740°N", "74.005974°W"),
                 "London":("51°30′26″N", "0°7′39″W"),
                 "Dublin":("53°21′N", "6°16′W"),
                 "Paris":("48°51′24″N", "2°21′08″"),
                 "Berlin":("52°31′12″N", "13°24′18″E"),
                 "Amsterdam":("52°22′N", "4°54′E"),
                 "Oslo":("59°54′50″N", "10°45′8″E"),
                 "Vienna":("48°12′N", "16°22′E"),
                 "Helsinki":("60°10′15″N", "24°56′15″E")};

# Get a ditionary view on keys
keysView = cityVsLatLong.keys();

print("Type of dictionary view: %s"%type(keysView));

placeToFind = "Nili Fossae";

# Check for membership
if placeToFind in keysView:
    print("Found the place:%s"%placeToFind);
else:
    print("Place not found:%s"%placeToFind);

# Print each key in the view
print("--Printing the dictionary keys from the view:--");
for key in keysView:
    print(key);

Output:

Type of dictionary view: <class 'dict_keys'>
Place not found:Nili Fossae
--Printing the dictionary keys from the view:--
Washington, D.C.
New York City
London
Dublin
Paris
Berlin
Amsterdam
Oslo
Vienna
Helsinki

 


Copyright 2023 © pythontic.com