字典练习 1
Python 程序通过从给定字典中提取键来创建新字典。
d1 = {"one":11, "two":22, "three":33, "four":44, "five":55}
keys = ['two', 'five']
d2={}
for k in keys:
d2[k]=d1[k]
print (d2)
它将产生以下输出 -
{'two': 22, 'five': 55}
字典练习 2
Python 程序将字典转换为 (k,v) 元组列表。
d1 = {"one":11, "two":22, "three":33, "four":44, "five":55}
L1 = list(d1.items())
print (L1)
它将产生以下输出 -
[('one', 11), ('two', 22), ('three', 33), ('four', 44), ('five', 55)]
字典练习 3
Python 程序删除字典中具有相同值的键。
d1 = {"one":"eleven", "2":2, "three":3, "11":"eleven", "four":44, "two":2}
vals = list(d1.values())#all values
uvals = [v for v in vals if vals.count(v)==1]#unique values
d2 = {}
for k,v in d1.items():
if v in uvals:
d = {k:v}
d2.update(d)
print ("dict with unique value:",d2)
它将产生以下输出 -
dict with unique value: {'three': 3, 'four': 44}
字典练习计划
- Python 程序按值对字典列表进行排序
- Python 程序从给定字典中提取每个键都具有非数字值的字典。
- Python 程序,用于从两个项 (k,v) 元组的列表构建字典。
- Python 程序合并两个 dictionary 对象,使用 unpack 运算符。