Chapter 7


1.

Dictionary methods

dict.update()


3.

Dictionary methods

  1. keys = dict.keys() keys.sort()

    or

    sorted(dict.keys())

4.

Creating dictionaries

# assumes and list2 are the same length d = {} for i in range(len(list1)):     d[list1[i]] = list2[i]


or

d = {} for i, x in enumerate(list1):     d[x] = list2[i]


or

d = dict(map(None, list1, list2))


or

d = dict(zip(list1, list2))


7.

Inverting dictionaries

list1 = oldDict.values() list2 = oldDict.keys()


Now apply the solutions to Problem 4.

Note that these solutions are destructive, meaning that for one-to-many dictionaries, keys that share the same values will only have the latest installed value for the value that is now a key. Extra Credit: Come up with a non-destructive solution where keys that share the same values in the old dictionary are now stored inside a list as the value for the corresponding key in the new dictionary.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net