python: data structure - dictionaries

  • dictionaries are extremely efficient at looking up a value, given a specific key object that maps to that value. there is a key and the corresponding value associated with that key for each dictionary item.
  • create a dictionary: dict() or {}
stock = {"FB":(100,101,99,100),
         "GOOG":(1000,1001,999,1001)}

>>> stock["FB"]
(100,101,99,100)
  • if you are looking for an item that does not in the dictionary:
>>> stock["RIM"]

KeyError                                  Traceback (most recent call last)
<ipython-input-135-815943ffd2a8> in <module>()
      1 stock = {"FB":(100,101,99,100),
      2          "GOOG":(1000,1001,999,1001)}
----> 3 stock["RIM"]

KeyError: 'RIM'
  • dictionary method: get()
# get() accepts a key as the first parameter and an optional default value if the key does not exist:
>>> print(stock.get("RIM")
None
>>> stock.get("RIM","Not Found")
'Not Found'
  • dictionary method: keys(), value(), items(). items() is most useful since it returns an iterator over tuples of (key, value) pairs for every item in the dictionary. this works great with tuple unpacking in a for loop to loop over associated keys and values.
for symbol, values in stock.items():
    print ("{} last value is {}".format(symbol,values[0]))
  • use setdefault() method to control dictionary: if the key is in the dictionary, setdefault() behaves like get(): it returns the value for that key. otherwise, if the key is not in the dictionary, it will not only return the default value we supply in the method call, it will also set the key to that same value we supply.
>>> stock.setdefault("GOOG","Not Found")
(1000,1001,999,1001)
>>> stock.setdefault("BBRY",(100,101,102,103))
(100,101,102,103)

>>> stock["BBRY"] #stock.get("BBRY")
(100,101,102,103)
  • due to an efficient algorithm (known as hasing), the dictionary items are inherently unsorted.
  • values in dictionary items are not immutable.
  • keys with different types can be used in the same dictionary

defaultdict

  • we already see the use of setdefault():
def letter_frequency(sentence):
    frequencies = {}
    for letter in sentence:
        frequency = frequencies.setdefault(letter, 0)
        frequencies[letter] = frequency + 1
    return frequencies

>>> letter_frequency("this is a short sentence that is used for testing")
{'t': 7,
 'h': 3,
 'i': 4,
 's': 7,
 ' ': 9,
 'a': 2,
 'o': 2,
 'r': 2,
 'e': 5,
 'n': 3,
 'c': 1,
 'u': 1,
 'd': 1,
 'f': 1,
 'g': 1}
  • Every time we access the dictionary, we need to check that it has a value already, and if not, set it to zero. When something like this needs to be done every time an empty key is requested, we can use a different version of the dictionary, called defaultdict(). The defaultdict accepts a function in its constructor. Whenever a key is accessed that is not already in the dictionary, it calls that function, with no parameters, to create a default value. 

from collections import defaultdict
def letter_frequency(sentence):
    frequencies = defaultdict(int)
    for letter in sentence:
        frequencies[letter] += 1
    return frequencies
>>> letter_frequency("this is a short sentence that is used for testing")
defaultdict(int,
            {'t': 7,
             'h': 3,
             'i': 4,
             's': 7,
             ' ': 9,
             'a': 2,
             'o': 2,
             'r': 2,
             'e': 5,
             'n': 3,
             'c': 1,
             'u': 1,
             'd': 1,
             'f': 1,
             'g': 1})

猜你喜欢

转载自blog.csdn.net/zhangxlubc/article/details/84298351