如何解决过滤python字典中的前3个值
我有这样的字典:
mydict = {1: {'shooting': 9,'photography': 43,'portrait': 17,'portraitphotography': 4,'model': 40,'modeling': 10,'lovemyjob': 13,'buzzcut': 86}
2: {'lowbun': 18,'sleekhair': 4,'girl': 94,'profile': 4,'lips': 31,'choker': 16,'gold': 16,'minimalist': 1}
3: {'chaching': 1,'newhair': 20,'happy': 31,'besthairdresser': 2,'hairdresser': 85,'treatyoself': 1,'loveit': 12,'brunette': 36,'foils': 325}
我想获取每个字典中的前3个值,因此它应该看起来像这样:
{1: {'buzzcut': 86
'photography': 43,'model': 40}
2: {'girl': 94,'lowbun': 18}
3: {'foils': 325
'hairdresser': 85,'brunette': 36}
我尝试使用
mydict = dict(sorted(mydict.iteritems(),key=operator.itemgetter(1),reverse=True)[:3])
但出现错误not supported between instances of 'dict' and 'dict'
有人可以帮忙吗?
解决方法
使用collections.Counter
的简单高效的方法:
>>> {k: dict(Counter(mydict[k]).most_common(3)) for k in mydict}
{1: {'buzzcut': 86,'photography': 43,'model': 40},2: {'girl': 94,'lips': 31,'lowbun': 18},3: {'foils': 325,'hairdresser': 85,'brunette': 36}}
,
您可以使用sorted()按值对字典进行排序,它将返回给您一个元组的排序列表,其中第一个包含键,第二个包含键的值
<Form>
{/* other components */}
<button
type="reset"
className="outline"
disabled={!dirty || isSubmitting}
>
Reset
</button>
</Form>
将前3个放到字典中就可以了
sorted_values_1 = sorted(mydict[1].items(),key=lambda x: x[1],reverse=True)
#In this example it will return:
#[('buzzcut',86),('photography',43),('model',40),('portrait',17),('lovemyjob',13),('modeling',10),('shooting',9),('portraitphotography',4)]
,
您可以通过简单的字典理解来做到这一点:
q = {
j: dict(sorted(
mydict[j].items(),key=lambda item: item[1],reverse=True)[:3])
for j in mydict
}
结果:
>>> print(q)
{1: {'buzzcut': 86,'brunette': 36}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。