简体   繁体   English

使用多个值对 Python 中的字典进行排序

[英]Sorting a dict in Python with multiple values

Lets say I have 2 dicts like可以说我有 2 个像

A = {'a':1, 'b':2, 'c':2}
B = {'a':5, 'b':7, 'c':6}

I want to sort dict A based on value of dict A .我想根据 dict A的值对 dict A进行排序。 If there the value is same, it must use the value from B to resolve the sorting.如果存在相同的值,则必须使用来自 B 的值来​​解决排序问题。 Eg: For keys 'b' and 'c', with same values in dict A , it must use values 7 and 6 from dict B to resolve it.例如:对于键 'b' 和 'c',在 dict A具有相同的值,它必须使用来自 dict B值 7 和 6 来解决它。

Assuming a and b both have same keys:假设ab都有相同的键:

a = {'a':1, 'b':0, 'c':2}
b = {'a':5, 'b':77, 'c':6}

dict(sorted(a.items(), key=lambda x: ( x[1], b[x[0]] ), reverse=True))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM