info = {'101': 'Luola','102': 'Maliya', '103':'Alex'} 方式一: for key in info: print(key,info[key]) print (30*'$') 方式二: for k,v in info.items(): print(k,v)
输出字典的项 for d in info.items(): print(d) print (30*'$') 输出key for a in info.keys(): print(a) print (30*'$') 输出value for b in info.values(): print(b)
#字典增加
dict1 = {'name': 'Rose', 'age': 30, 'sex': '女'}
dict1['id'] = 1010
print(dict1)
# 结果 {'name': 'Lisa', 'age': 30, 'sex': '女', 'id': 1010}
#字典删除
del
l1 = [ 1, 2, 3 ]
l2 = [ 'x', 'y', 'z']
l3 = [ 'x', 'y' ]
print(dict(zip(l1,l3)))
{1: 'x', 2: 'y'}
kk=input()
nickey={'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}
扫描二维码关注公众号,回复:
16902221 查看本文章
for aa in nickey.keys():
if aa==kk:
for mm in nickey[aa]:
print(mm,end=" ")
.Python的字典可以用来计数,让要被计数的元素作为key值,它出现的频次作为value值,只要在遇到key值后更新它对应的value即可。现输入一个单词,使用字典统计单词中各个字母出现频次。
x = {} y = input() for i in y: x[i] = y.count(i) print(x)
import operator dic_instance = {3: 1, 2: 23, 1: 17} sort_key_dic_instance = dict(sorted(dic_instance.items(), key=operator.itemgetter(0))) #按照key值升序 sort_val_dic_instance = dict(sorted(dic_instance.items(), key=operator.itemgetter(1))) #按照value值升序 print(sort_key_dic_instance) # output:{1: 17, 2: 23, 3: 1} print(sort_val_dic_instance) # output:{3: 1, 1: 17, 2: 23}