字典练习

dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}

# 1.遍历出所有的key

for key in dic:
    print(key)

# 2.遍历出所有的value

for key in dic:
    print(dic[key])

# 3.遍历出所有的key和value

for key in dic:
    print(key, dic[key])

for key, value in dic.items():  #效率低
    print(key, value)

# 4.在字典添加一个键值对,’k4’:’v4’,输出添加后的字典

dic['k4'] = 'v4'
print(dic)

# 5.删除键值对'k1','v1'并输出

dic.pop('k1')
del dic['k1']
dic.popitem() # 随机返回并删除字典中的一对键和值(一般删除末尾对)。
print(dic)

# 6.删除字典中的键'k5'对应的键值对,如果字典不存在键'k5',则不报错,并且让其返回None

if dic.get('k5'):
    dic.pop('k5')
else:
    print(dic.get('k5'))

# 7.请获取字典中k2对应的值

k2_value = dic.get('k2')
print(k2_value)

# 8.请获取字典中'k6'对应的值,如果键'k6'不存在,则不报错,并且让其返回None

k6_value = dic.get('k6')
if not k6_value:
    print(k6_value)


# 9.现有dic2 ={‘k1’:’v111’,’a’:’b’}通过一行操作使dic2 = {‘k1’:’v1’,’k2’:’v2’,’k3’:’v3’,a’:’b’}

dic2 = {'k1': 'v111', 'a': 'b'}
dic2.update({'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'a': 'b'})
print(dic2)

# 10 组合嵌套题
lis = [['k', ['qwe', 20, {'k1': ['tt', 3, '1']}, 89], 'ab']]

# a.将列表list中的'tt'变成大写(用两种方式)

lis[0][1][2]['k1'][0] = 'TT'
print(lis)
lis[0][1][2]['k1'].remove('tt')
lis[0][1][2]['k1'].insert(0, 'TT')
print(lis)

lis[0][1][2]['k1'][0] = lis[0][1][2]['k1'][0].upper()
print(lis)

# b.将列表list中的数字3变成字符串'100'(用两种方式)

lis[0][1][2].update({'k1': ['tt', '100', '1']})
print(lis)

lis[0][1][2]['k1'][1] = '100'
print(lis)
lis[0][1][2]['k1'][1] = lis[0][1][2]['k1'][1]

lis[0][1][2]['k1'].remove(3)
lis[0][1][2]['k1'].insert(1, '100')
print(lis)


# c.将列表list中的字符串'1'变成数字101(用两种方式)

lis[0][1][2]['k1'][2] = 101
print(lis)

lis[0][1][2]['k1'][2] = int(lis[0][1][2]['k1'][2].replace('1', '101'))
print(lis)

# 总结:就是从三个层面修改:1.列表 2.字典 3.字符串

 

li = [1, 2, 3, 'a', 'b', 4, 'c']

dic = {}

dic.setdefault('k1', [])

for odd in li:
    if li.index(odd) % 2 != 0:
        dic['k1'].append(odd)
print(dic)

 

 

 

转载于:https://www.cnblogs.com/lshedward/p/9929374.html

### Python 字典练习题 #### 示例题目一:统计文本中单词数量并找出频率最高的五个词 给定一段纯文字的字符串,去除所有标点符号后,统计该段落内不同单词的数量,并找到出现次数最多的前五名。 ```python from collections import Counter import re def word_frequency(text): words = re.findall(r'\b\w+\b', text.lower()) counts = Counter(words) most_common_words = counts.most_common(5) unique_word_count = len(counts) return { "unique_word_count": unique_word_count, "top_5_frequent_words": dict(most_common_words), } text_input = """ Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation. """ result = word_frequency(text_input) print(f"Unique Words Count: {result['unique_word_count']}") print("Top 5 Frequent Words:") for word, freq in result["top_5_frequent_words"].items(): print(f"{word}: {freq}") ``` 此代码片段展示了如何处理输入文本以计算唯一单词计数和最高频率词汇表[^2]。 #### 示例题目二:修改嵌套字典结构 基于提供的初始字典`dic1`,执行一系列操作来改变其内部: - 向"name"列表添加新成员"wusir" - 将"name"列表内的所有实例'dxl'转换成大写字母'DXL' - 增添新的键对到子字典"oldboy"下 - 移除特定项自"oldboy"下的另一个子列表 ```python dic1 = {'name': ['dxl', 2, 3, 5], 'job': 'teacher', 'oldboy': {'dxl': ['python1', 'python2', 100]}} # 添加元素至 name 列表 dic1["name"].append("wusir") # 修改 dxl 成 DXL for index in range(len(dic1['name'])): if isinstance(dic1['name'][index], str) and dic1['name'][index].lower() == 'dxl': dic1['name'][index] = 'DXL' # 新增键对于 oldboy 下面 dic1["oldboy"]["老男孩"] = "linux" # 删除 python2 自 oldboy -> dxl 的列表里 if "python2" in dic1["oldboy"]["dxl"]: dic1["oldboy"]["dxl"].remove("python2") print(dic1) ``` 这段脚本实现了上述四个任务的要求,同时也体现了对于复杂数据类型的灵活运用能力[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值