Home > Enterprise >  Sort dictionary based on values from a list
Sort dictionary based on values from a list

Time:09-22

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']}

CodePudding user response:

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']}

CodePudding user response:

You can do this

import pandas as pd


names = ['bread', 'banana', 'apple']
prices = ['2', '4', '1']
links = ['url_1', 'url_2', 'url_3']

val_dict = {'name': names, 'price': prices, 'link': links}

df = pd.DataFrame(val_dict)

df = df.sort_values('price').to_dict('list')

print(df)

Output:

{'name': ['apple', 'bread', 'banana'], 'price': ['1', '2', '4'], 'link': ['url_3', 'url_1', 'url_2']}
  • Related