Saturday, March 8, 2014

Python Study Note: Data Structure - Dict

"Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. "

Think dict as an unordered set of [key:value] pairs, with a requirement that the key is unique.

1. How to generate a dictionary?
    1.1 Direct way
        a = {}   --- empty dictionary
    1.2 Generator
        a = {x:x**2 for x in range(10)}
    1.3 Convert
        a = [[1,2], [2,3]]; b = dict(a);

2. Operators (what is in the dict?)
    2.1 a.keys()  --- return all keys as a list
    2.2 a.values()  --- return all values as a list, including duplicates
    2.3 a.has_key(x)  --- return True/False, based on whether dict has the key
    2.4 a.pop(x)  --- return the value for key x, and then remove the key:value list
    2.5 del a[x] --- directly delete the element from dict a
    2.6 a.update(b) --- add the entries in dict b into a


Now seems like the basic data structures in "raw" python is discussed. It is very interesting that the Python language fully utilized the keyboard: () as tuple, [] as list, and {} as dict. How interesting it is?

Btw, if one want to do some looping, then one can use enumerate() to generate a enumerate type for looping:

for i,j in enumerate(['this', 'is', 'a', 'good', 'day']:
    print i,j

while the generated enumerate type could be directly translated into list/tuple/dict by using list()/tuple()/dict() functions.

No comments:

Post a Comment