1. Computing

Transitioning from 2.x to 3.0

From , former About.com Guide

3 of 6

Dictionary Lists to Views
Several methods of the dictionary class that return a list under 2.5 and before now return a view. Under Pytho <=2.5, the value returned reflected the dictionary items at the time the method was called. If the dictionary changed immediately afterward, the list did not change. Views allow for dynamic assignment of dictionary items (or their sundry aspects). So, the values refleced in the calls will change with the dictionary. For most programming, this difference will not matter greatly. For example, see the following dictionary containing some of this year's Nobel Prize winners:
 >>> dict = {"1953":"Paul Krugman", "1921":"Yoichiro Nambu", "1944":"Makoto Kobayashi", "1940":"Toshihide Maskawa", "1928":"Osamu Shimomura", "1947":"Martin Chalfie", "1952":"Roger Y. Tsien"} 
 >>> keys = sorted(dict) 
 >>> for year in keys: 
 ... print(dict[year], year, sep=": ") 
 ... 
 Yoichiro Nambu: 1921 
 Osamu Shimomura: 1928 
 Toshihide Maskawa: 1940 
 Makoto Kobayashi: 1944 
 Martin Chalfie: 1947 
 Roger Y. Tsien: 1952 
 Paul Krugman: 1953 
 >>> dict["1937"]="Martti Ahtisaari" 
 >>> for year in keys: 
 ... print(dict[year], year, sep=": ") 
 ... 
 Yoichiro Nambu: 1921 
 Osamu Shimomura: 1928 
 Toshihide Maskawa: 1940 
 Makoto Kobayashi: 1944 
 Martin Chalfie: 1947 
 Roger Y. Tsien: 1952 
 Paul Krugman: 1953 
Note that we have not re-assigned the new list. Once we re-assign keys, however, the output of the loop changes.
 >>> keys = sorted(dict) 
 >>> for year in keys: 
 ... print(dict[year], year, sep=": ") 
 ... 
 Yoichiro Nambu: 1921 
 Osamu Shimomura: 1928 
 Martti Ahtisaari: 1937 
 Toshihide Maskawa: 1940 
 Makoto Kobayashi: 1944 
 Martin Chalfie: 1947 
 Roger Y. Tsien: 1952 
 Paul Krugman: 1953 
Dictionary methods that are now returning views instead of lists are dict.keys(), dict.items() and dict.values(). Also, some are no longer supported: dict.iterkeys(), dict.iteritems(), and dict.itervalues().
  1. About.com
  2. Computing
  3. Python
  4. Python 3.0
  5. Learn Python 3.0 - Python 3.0 Tutorials - Python 3.0 Transition Guide - Dictionary Lists to Views

©2013 About.com. All rights reserved.