关注微信公众号(瓠悠笑软件部落),一起学习,一起摸鱼
python 字典循环
# 循环values
spam = {'color': 'red', 'age': 42}
for v in spam.values():
print(v)
# 循环keys
for k in spam.keys():
print(k)
# 循环key和value
for i in spam.items():
print(i)
# if you want a true list from one of these methods. pass its list-like return value to the list() function.
print(spam.keys())
the_dict_keys = list(spam.keys())
print(the_dict_keys)
for k, v in spam.items():
print('Key:' + k + ' Value: ' + str(v))
判断一个key或者value是否在字典中存在
spam = {'name': 'Zophie', 'age': 7}
'name' in spam.keys() # result is true
'Zophie' in spam.values() # result is true
'color' in spam.keys() # result is false
'color' not in spam.keys() # result is true
'color' in spam # result is false
get() 方法
根据key查询字典,如果key不存在,就返回给定的默认值
picnicItems = {'apples': 5, 'cups': 2}
print('I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
print('I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
setdefault() 方法
在字典里面设置一个值,经常需要先检查这个值是否已经存在,代码如下:
spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'
setdefault()方法,先检查key存在不,如果不存在,就设置后面的值。如果存在,就返回已经存在的值,而不在进行设置。
spam = {'name': 'Pooka', 'age': 5}
spam.setdefault('color', 'black')
print(spam)
# 输出是: {'color': 'black', 'age': 5, 'name': 'Pooka'}
spam.setdefault('color', 'white')
print(spam)
# 输出是: {'color': 'black', 'age': 5, 'name': 'Pooka'}
统计字符串中字符出现的次数
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
pretty printing
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
print(pprint.pformat(count))