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})

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值