python字典循环

本文介绍了Python字典的循环方法,包括使用get()和setdefault()方法判断及设置键值,还讲述了如何统计字符串中字符出现的次数以及字典的美化输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关注微信公众号(瓠悠笑软件部落),一起学习,一起摸鱼
huyouxiao.com

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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值