1

How can I sort a dictionary using the values from a list?

names = ['bread', 'banana', 'apple']
prices = ['2', '4', '1']
...

dict = {'name': names, 'price': prices}

dict is now {'name': ['bread', 'banana', 'apple'], 'price': ['2', '4', '1']}

I want to sort the dictionary in a way that the first name corresponds to the lower price.

Is this possible to achieve with sorting on a dictionary?

Example

sorted_dict = {'name': ['apple', 'bread', 'banana'], price: ['1', '2', '4']}

martineau
  • 119,623
  • 25
  • 170
  • 301
André Clérigo
  • 846
  • 1
  • 10
  • 30

1 Answers1

3

IIUC, you want to sort the first list (in name) based on the values of the second list (in price).

If that's what you want, then a quick way is to use pandas, since the data structure you have (dict of lists), fits really nicely with a pd.DataFrame.

import pandas as pd

pd.DataFrame(d).sort_values('price').to_dict('list')
{'name': ['apple', 'bread', 'banana'], 'price': ['1', '2', '4']}

Added the example as per OPs modified request -

names = ['bread', 'banana', 'apple']
prices = ['2', '4', '1']
description = ['a','x','b']
...

d = {'name': names, 'price': prices, 'description':description}


pd.DataFrame(d).sort_values('price').to_dict('list')

{'name': ['apple', 'bread', 'banana'],
 'price': ['1', '2', '4'],
 'description': ['b', 'a', 'x']}
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51