Home > front end >  python - sort dictionary keys based on value
python - sort dictionary keys based on value

Time:10-19

I have a Python dictionary in the format:

my_dict = {'name': ['apple', 'orange', 'banana'],
           'quantity': [20, 10, 30],
           'price': [45, 50, 75]}

I first want to rank the fruits based on quantity so that I end up with an output like this:

['banana', 'apple', 'orange']

I then want to print out the ranked fruits along with their quantity and price so that it looks like:

>>> banana:
    price: 75
    quantity: 30
    
    apple:
    price: 45
    quantity: 20
    
    orange:
    price: 50
    quantity: 10

What I have attempted so far:

attempt = sorted(my_dict.items(), key=lambda x:x[0])
sorted(my_dict.items(), key=lambda t: t[::-1])

CodePudding user response:

You can use zip to combine the list elements of the 3 keys and sort the tuples that come out of the map() function (placing the quantity as the first element). Then iterate through those in a comprehension to format and print the result:

my_dic = {'name':['apple', 'orange', 'banana'],
          'quantity':[20, 10, 30],
          'price': [45, 50, 75]}

print(*( f"{n}:\nprice: {p}\nquantity: {q}\n"
         for q,n,p in sorted(zip(*map(my_dic.get,('quantity','name','price'))),
                             reverse=True) ),
      sep='\n')

banana:
price: 75
quantity: 30

apple:
price: 45
quantity: 20

orange:
price: 50
quantity: 10

CodePudding user response:

Here is one of the approached using pandas DataFrame:

import pandas as pd
my_dic = {'name':['apple', 'orange', 'banana'],
          'quantity':[20, 10, 30],
          'price': [45, 50, 75]}
# Convert to DataFrame
df = pd.DataFrame(my_dic)
# Sort based on quantity
df = df.sort_values(by=['quantity'], ascending=False)
# Get a dict format of dataframe and print as required
my_dic = df.to_dict('dict')
print (my_dic['name'].values())
for key in my_dic['name'].keys():
    print (my_dic['name'][key])
    print (f"price: {my_dic['price'][key]}")
    print(f"quantity: {my_dic['quantity'][key]}")

Output:

dict_values(['banana', 'apple', 'orange'])
banana
price: 75
quantity: 30
apple
price: 45
quantity: 20
orange
price: 50
quantity: 10

CodePudding user response:

You can do sth like this:

extracted_dict = {name: {'price':  my_dic['price'][i], 'quantity': my_dic['quantity'][i]} for i, name in enumerate(my_dic['name'])}

This gives you sth like this:

{'apple': {'price': 45, 'quantity': 20}, 'orange': {'price': 50, 'quantity': 10}, 'banana': {'price': 75, 'quantity': 30}}

Then you can sort that:

print(sorted(extracted_dict, key=lambda x: extracted_dict[x]['quantity']))

CodePudding user response:

Oh... I was fourth...

d = {'name':['apple', 'orange', 'banana'],
          'quantity':[20, 10, 30],
          'price': [45, 50, 75]}

r = []

for a,b,c in zip(d['name'],d['quantity'],d['price']):
  r.append({'name': a,'quantity': b,'price': c})

sorted_r = sorted(r, key=lambda x: -x['quantity'])

for a in sorted_r:
  print(a['name'])
  print(a['quantity'])
  print(a['price'])
  print('----')
banana
30
75
----
apple
20
45
----
orange
10
50
----
  • Related