循环打印字典打印出来的是键:
dic = {"k1": "v1v1", "k2": [11,22,33,44]} for i in dic: print(i) #打印: k1 k2
这时可以利用键值查找字典对应的value,如果字典里边的value为列表,还可以通过它进行各种操作,比如切片:
#检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并打印 dic = {"k1": "v1v1", "k2": [11,22,33,44]} for i in dic: if len(dic[i]) > 2: dic[i] = dic[i][0:2] print(dic) #打印: {'k1': 'v1', 'k2': [11, 22]}