0

I have a dictionary as follows:

test = {
    "Name": ["Bimal", "Kamal", "Hari", "Ram", "Shyam"],
    "Age": [12, 24, 23, 19, 17]
}

and I want to sort it based on name so that the age of Kamal must remain 24 after sorting. So, what I want as final dictionary is:

test = {
    "Name": ["Bimal", "Hari", "Kamal", "Ram", "Shyam"],
    "Age": [12, 23, 24, 19, 17]
}

I can easily do it with pandas but I wanted an efficient way to do it without using pandas. Is there any way to do it efficiently?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Bimal Timilsina
  • 81
  • 2
  • 12

1 Answers1

4

You could use zip method.

test = {
   "Name": ["Bimal", "Kamal", "Hari", "Ram", "Shyam"],
   "Age": [12, 24, 23, 19, 17]
}

print(*zip(*sorted(zip(test["Name"], test["Age"]))))

The result of this will consists in two tuples and then you can convert to lists.

result = list(zip(*sorted(zip(test["Name"], test["Age"]))))
test = {
  "Name": list(result[0]),
  "Age": list(result[1])
}
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • 1
    Thank you! I was thinking about taking the indices of each list items before and after and sort other key values accordingly! but that was too much time and space consuming process! – Bimal Timilsina Nov 19 '20 at 07:30