Zero404NF
Zero404NF

Reputation: 19

How do I keep dictionary both key and value while sorting? (python)

item = {"num1":[1,3] , "num2": [2,4]}

wanted output

num1:1
num2:2
num1:3
num2:4

(basically order by value but some how keep the key it came with it doesn't have to be in a dictionary as long as the output is order by value)

I'm completely stump atm any help would be much appreciated

Upvotes: 1

Views: 34

Answers (1)

Boseong Choi
Boseong Choi

Reputation: 2596

  1. Make pairs(2-tuples) with key-elements.
  2. Sort it with second key. (sorted(target, key=lambda x: x[1]))
item = {'num1': [1, 3], 'num2': [2, 4]}
result = sorted(
    [
        (k, v)
        for k, list_ in item.items()
        for v in list_
    ],
    key=lambda x: x[1],
)
print(result)
for r in result:
    print(f'{r[0]}:{r[1]}')

output:

[('num1', 1), ('num2', 2), ('num1', 3), ('num2', 4)]
num1:1
num2:2
num1:3
num2:4

@OldBill's solution:

  • By reordering elements of tuples, you can use tuple itself for sorting key.
  • If you use tuple unpacking in for-loop, it become more readable.
item = {'num1': [1, 3], 'num2': [2, 4]}
result = sorted([
    (v, k)
    for k, list_ in item.items()
    for v in list_
])
print(result)
for v, k in result:
    print(f'{k}:{v}')

output:

[(1, 'num1'), (2, 'num2'), (3, 'num1'), (4, 'num2')]
num1:1
num2:2
num1:3
num2:4

Upvotes: 3

Related Questions