MIT Python学习基础系列(二) - dictionary

Dictionaries

Strings, tuples, ranges, lists

Common operations
  • seq[i]
  • len(seq)
  • seq1 + seq2 (not ranges)
  • n*seq -> sequence that repeats seq n times ( not ranges )
  • seq[start:end]
  • 3 in seq
  • 3 not in seq
  • for e in seq -> iterates over elements of sequence
  • Properties
  • Only lists are mutable

    Dictionaries

  • Index item of interest directly (not always int)
  • Use one data structure
  • A python dictionary { }
Store pairs of data
Key : Value
my_dict = {} 
grades = {‘John’: ‘A+’, ‘Katy’:’A’}

Operations

  • Add an entry:
grades[‘Sylvan’] = ‘B+’
  • Remove an entry:
del(grades[‘Ana’])
  • Copy a dict:
dict2 = dict(dict1) 
or 
dict2 = dict1.copy()
  • Test if a key is in the dictionary:
‘Daniel’ in grades
  • Get an iterable that acts like a tuple of all keys:
grades.keys() # [‘Ana’,’Ben’]
  • Get an iterable that acts like a tuple of all values:
grades.values()
  • Safe way to access a value if we are not sure the key is in the dictionary:
d.get(key, default)

Keys and Values

Values

  • Can be any type (immutable or mutable)
  • Can be duplicates
  • Can be lists, even other dictionaries

Keys

  • Must be unique
  • Immutable type(int, float, string, tuple, bool)
  • Need an object that is hashable, all immutable types are hashable
  • Careful with float type as a key
  • No order to keys or values

Examples with a Dictionary

  • Fibonacci and dictionaries
Recursive fibonacci is ineffective because it keeps recalculating
Store the already-calculated result in a dictionary to save the recalculating
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值