woonizzooni

[Python] dict -> ['(key, value)'] sorted array 만들기 (value로 > 그 이후 key로) 본문

Programming/Python

[Python] dict -> ['(key, value)'] sorted array 만들기 (value로 > 그 이후 key로)

woonizzooni 2020. 10. 10. 18:32

value(정수)으로 정렬 후 동일 값일 경우 key로 정렬을 시도할 것이다.

 

python2.x

 - dict.viewitems(), dict.iteritems(), ...

Python 2.7.16 (default, Jun  5 2020, 22:59:21)
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> d={'apple':2, 'banana':3, 'almond':2, 'beetroot':3, 'peach':4}

>>> [(k,v) for k, v in sorted(d.iteritems(), key=lambda(k, v): (-v, k))]
[('peach', 4), ('banana', 3), ('beetroot', 3), ('almond', 2), ('apple', 2)
'
>>> [(k,v) for k, v in sorted(d.iteritems(), key=lambda(k, v): (v, k))]
[('almond', 2), ('apple', 2), ('banana', 3), ('beetroot', 3), ('peach', 4)]

 

 

python3.x

  - 위 코드 그대로 복붙하면 "SyntaxError: invalid syntax"

  - dict.items(), ...

Python 3.7.6 (default, Jan 27 2020, 20:19:29)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'apple':2, 'banana':3, 'almond':2, 'beetroot':3, 'peach':4}

>>> [(k,v) for k, v in sorted(d.iteritems(), key=lambda(k, v): (-v, k))]
  File "<stdin>", line 1
    [(k,v) for k, v in sorted(d.iteritems(), key=lambda(k, v): (-v, k))]
                                                       ^
SyntaxError: invalid syntax

>>> sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))
[('peach', 4), ('banana', 3), ('beetroot', 3), ('almond', 2), ('apple', 2)]

>>> sorted(d.items(), key=lambda kv: (kv[1], kv[0]))
[('almond', 2), ('apple', 2), ('banana', 3), ('beetroot', 3), ('peach', 4)]

 

 

ref

https://docs.python.org/3/howto/sorting.html#sortinghowto

https://www.python.org/dev/peps/pep-3113/

 

Comments