my_dict = {‘name‘:‘coop‘,‘time‘:8.8}
my_dict
{‘name‘: ‘coop‘, ‘time‘: 8.8}
my_dict[‘beijing‘]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-6-8c49445fad86> in <module>()
----> 1 my_dict[‘beijing‘]
KeyError: ‘beijing‘
my_dict.get(‘beijing‘,‘ ‘) # 字典的默认输出之设置方法,避免报错
‘ ‘
my_dict.get(‘beijing‘) # 如果没有设置空,则不打印任何东西
from collections import defaultdict
todo = defaultdict(lambda:‘nothing...‘)
type(todo)
collections.defaultdict
todo[‘222‘] = ‘buybuy‘
todo
defaultdict(<function __main__.<lambda>()>, {‘222‘: ‘buybuy‘})
todo[‘beijing‘] # 该字典中没有该key,也不会报错,只会打印出默认的‘nothing
‘nothing...‘
#!/usr/bin/env Python
# -*- coding:utf-8 -*-
# 51memo.1.py
# A memo demo 51备忘录
# author: De8uG
__author__ = ‘De8uG‘
desc = ‘51备忘录‘.center(30, ‘-‘)
print(desc)
welcome = ‘welcome‘
print(f‘{welcome}‘, __author__)
print(‘请输入备忘信息:‘)
all_memo = []
# TODO:这里要继续完成某个代码
is_add = True
all_time = 0
while(is_add):
in_date = input(‘日期:‘)
in_thing = input(‘事件:‘)
in_time = input(‘用时:‘)
print(‘待办列表‘.center(30, ‘-‘))
#one = ‘{date}, 处理{thing}, 用时{time}‘.format(date=in_date, thing=in_thing,time=in_time)
one = {}
one[‘date‘] = in_date # in_date即上面的变量
one[‘thing‘] = in_thing
one[‘time‘]= in_time
all_memo.append(one)
all_time += int(in_time)
num = 0
for m in all_memo:
num += 1
print(‘%s:%s‘ %(num, m))
print(f"{num}:{m}")
print("{num1}:{m1}".format(num1=num,m1=m))
print(f‘共{len(all_memo)}条待办事项, 总时长:{all_time}。‘, end=‘‘)
print(‘(y:继续添加,n: 退出)‘)
is_add = input().strip() == ‘y‘
------------51备忘录-------------
welcome De8uG
请输入备忘信息:
日期:2
事件:3
用时:4
-------------待办列表-------------
1:{‘date‘: ‘2‘, ‘thing‘: ‘3‘, ‘time‘: ‘4‘}
1:{‘date‘: ‘2‘, ‘thing‘: ‘3‘, ‘time‘: ‘4‘}
1:{‘date‘: ‘2‘, ‘thing‘: ‘3‘, ‘time‘: ‘4‘}
共1条待办事项, 总时长:4。(y:继续添加,n: 退出)
n
原文地址:http://blog.51cto.com/13118411/2108345