Python 字典练习
示例 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)
它将产生以下 output −
[('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}