基础知识

字典类型用来描述加菲猫的特点再合适不过{'姓名':'加菲猫','颜色':'橙色带黑色条纹','身材':'肥胖','爱好':'吃和睡'},

加菲猫也仗义滴帮助我们把对字典的键值、值、条目的提取,行为函数的使用讲清楚。

作为一个仪式感很强的人(其实我不是,临时装一下),

我不想错过朋友生日那天送礼物送祝福,所以我要把朋友们的生日记录到字典类型的“数据库”里了......这是第一个程序实例

# Complete birthday database

# current database
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
print(birthdays)

# loop to perfect birthday database
while True:

	# input name which decides next step
	name = input("Enter a name(blank to quit): ")

	# exit, exist already, no record
	if name == '':
		break
	elif name in birthdays:
		print('{} is the birthday of {}'.format(birthdays[name], name))
	else:
		print('I do not have birthday information for ', name)
		bday = input('What is the birthday? ')
		birthdays[name] = bday
		print('Birthday database updated')

print(birthdays)


我需要给客户发一封溢美之词的邮件,最好能把TA忽悠晕了,明年好订购更多我司的产品。

要让客户觉得TA对我司是尊贵哒&独一无二哒,那邮件的称呼就不能是“尊贵的客户”,这一下子就被识破是群发啦!至少也的是“尊贵的王先生”or “尊贵的李小姐”......

我们的第二个程序实例就干了这个,通过客户的名字和性别,自动生成独特称谓的群发邮件内容

# ---------- PROBLEM : CREATE A CUSTOMER LIST ----------
# Create an array of customer dictionaries
# Input should look like this
'''
Enter Customer (Yes/No) : yes
Enter Customer Name&gender : Harry Potter male
Enter Customer (Yes/No) : Yes
Enter Customer Name&gender : Sherlock Holmes male
Enter Customer (Yes/No) : y
Enter Customer Name&gender : Taylor Swift female
Enter Customer (Yes/No) : no
'''
# Output should look like this
'''
Dear XX XXXX,

As our distinguished customer, you......

'''

# initiate the customer
customers = []

# loop
while True:

	# input and cut off the 1st letter to cover user's input
	createEntry = input("Enter customer(yes/no)? ")
	createEntry = createEntry[0].lower()

	#y or n
	if createEntry != 'y':
		break
	else:
		fName, lName, gender = input('Enter custer\'s name&gender: ').split()
		customers.append({'fName':fName,'lName':lName,'gender':gender})

# customize mail
for cust in customers:

	# title
	if cust['gender']=='male':
		title = 'Mr ' + cust['lName']
	else:
		title = 'Ms ' + cust['lName']

	# print the maile
	print('''Dear {},

As our distinguished customer, you......

	'''.format(title))


听说有投资机构专门统计特朗普推特内容单词出现的频率,然后通过频率高的词以及变化来分析政策走向。不知这传言靠不靠谱,更不知这种分析风马牛相不相及。

但我们的程序实例是靠谱哒,借助于字典这种数据类型,我们相当轻松的统计出一段文字里各个单词出现的次数

import pprint

# message
message = '''
Books and doors are the same thing books. 
You open them, and you go through into another world.
'''

# split message to words into a list
words = message.split()

# define dictionary counter
count = {}

# traverse every word and accumulate
for word in words:
	if not word[-1].isalpha():
		word = word[:-1]
	word = word.lower()
	count.setdefault(word, 0)
	count[word] +=1

print(count)
pprint.pprint(count)


小伙伴们一起出去野餐,

先商量一下各自打算都奉献啥:楚留香说“10个苹果、20个橘子”,李寻欢“20个鸡翅、2斤葡萄”,林诗音烤了培根和香肠,苏蓉蓉说会带苹果和鸡翅......

等一下,是不是应该统计下每种食物的数量啦!我们需要一个程序做这件事(才不要浪费自己的时间呐!)。

在字典这种数据类型的帮助下,我们很轻松就写出了一个这样的程序。

# Guest & items
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
                'Bob': {'ham sandwiches': 3, 'apples': 2},
                'Carol': {'cups': 3, 'apple pies': 1}}

# function: get amount of a item(allGuests, item)
def totalBrought(guests, item):

	# initiate a counter
	numBrought = 0

	# traverse values of all guests
	for v in guests.values():
			# accumulate the item
			numBrought += v.get(item, 0)

	return numBrought

print("Number of things being brought: \n")

print("-Apple				{}".format(totalBrought(allGuests,'apples')))
print("-Cups  				{}".format(totalBrought(allGuests,'cups')))
print("-Pretzel  			{}".format(totalBrought(allGuests,'pretzels')))
print("-Ham Sandwiches  	{}".format(totalBrought(allGuests,'ham sandwiches')))
print("-Apple  Pies 		{}".format(totalBrought(allGuests,'apple pies')))


最后我们介绍了集合这种数据类型,并用集合优化了我们的“野餐”程序,大为增加了程序的灵活性。

# Guest & items
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
                'Bob': {'ham sandwiches': 3, 'apples': 2},
                'Carol': {'cups': 3, 'apple pies': 1}}

# function: get amount of a item(allGuests, item)
def totalBrought(guests, item):

	# initiate a counter
	numBrought = 0

	# traverse values of all guests
	for v in guests.values():
			# accumulate the item
			numBrought += v.get(item, 0)

	return numBrought

foodSet = set()
for v in allGuests.values():
	foodSet |= set(v)
# print number of items (call function)
print("Number of things being brought: \n")

for food in foodSet:
	print("-{:20}			{}".format(food, totalBrought(allGuests, food)))



字典基础知识、记录生日和批量写邮件:
 
统计单词个数、野餐策划和集合的使用:
 

1 1 1 1 1 1 1 1 1 1 Rating 2.75 (4 Votes)