【跟着MIT学Python】Unit 3.6 Dictionaries

Dictionaries

Collection of things costumized with keys instead of numbers

list
0item 1
1item 2
2item 3
3item 4
dictionary
key 1value 1
key 2value 2
key 3value 3
key 4value 4
my_dict = {}
grades = {'Anna': 'B', 'John': 'A+','Denise':'A', 'Katy':"A"}

Dictionary operations

  • add
grades['Sylvan'] = 'A'
# mutable
  • test
'John' in grades
  • remove
del(grades['Anna'])
  • get an iterable acts like a tuple of all keys
grades.keys()
Out: dict_keys(['Anna', 'John', 'Denise', 'Katy'])
  • get an iterable acts like a tuple of all values
grades.value()
Out: dict_values(['B', 'A+', 'A', 'A'])

characteristic

grades
Out[62]: {'Anna': 'B', 'John': 'A+', 'Denise': 'A', 'Katy': 'A'}

type(grades)
Out[63]: dict

type(grades.values())
Out[65]: dict_values

type(grades['John'])
Out[72]: str

Example with a dictionary

def lyrics_to_frequencies(lyrics):
	myDict = {}
for words in lyrics:
	if words in myDict:
		myDict[words] += 1
	else:
		myDict[words] = 1
return myDict
# Find the biggest value numbers in a dictionary
animals = {'a':'aaa','b':'bbb', 'c':'ccc', 'd': ['ddd','dddd']}
result = None
biggestvalue = 0
for i in animals:
	if len(animals[i]) >= biggestvalue  ## here! the expression
	result = i
return result
  • Fibonacci with a dictionary
def fib_efficient(n,d):
	if n in d: 
		return d[n]
	else:
		ans = fib_efficient(n-1, d) +fib_efficient(n-2, d)
		d[n] = ans
		return ans
		
# do a lookup first in case already calculated the value
# modify dictionary as progress through function calls

fib_efficient(20,{1:1,2:2})
Out[7]: 10946
  • Global Variables
def fib(n);
	global numFibCalls # Here is something that I 
										# can access out of the scope
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值