1.对字典按值排序
得到元组列表,reverse=True为倒序
dup_name = sorted(dup_name.items(),key=lambda x:x[1],reverse=True)
dup_name
[('周鑫', 3),
('吴昊', 3),
('陈锋', 3),
('张博', 3),
('张一帆', 3),
('李志鹏', 3)]
2.设置默认值
(来源:利用Python进行数据分析2,ch3)
这是常见的情况,我们的值在另一个列表中。
In [123]: words = ['apple', 'bat', 'bar', 'atom', 'book']
In [124]: by_letter = {}
In [125]: for word in words:
.....: letter = word[0]
.....: if letter not in by_letter:
.....: by_letter[letter] = [word]
.....: else:
.....: by_letter[letter].append(word)
.....:
In [126]: by_letter
Out[126]: {'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']}
我们可以通过setdefault方法,写一段更为pythonic的代码
for word in words:
letter = word[0]
# 默认值为空列表
by_letter.setdefault(letter, []).append(word)
3. 字典键值对互换
{key:value for v,k in d1.items()}