简体   繁体   English

python - 根据值对字典键进行排序

[英]python - sort dictionary keys based on value

I have a Python dictionary in the format:我有一个格式如下的 Python 字典:

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:我首先想根据quantity对水果进行排名,以便最终得到如下输出:

['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])

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).您可以使用 zip 组合 3 个键的列表元素,并对来自 map() 函数的元组进行排序(将数量作为第一个元素)。 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

Here is one of the approached using pandas DataFrame :这是使用pandas DataFrame的方法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

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

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
----

Here my suggestion of a solution, a bit more lengish, but hopefully very clear:这是我对解决方案的建议,有点冗长,但希望非常清楚:

import pprint

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

# Convert that info into a better structure
fruits = {}
for index, fruit in enumerate(my_dic["name"]):
    fruits[fruit] = {
        "quantity": my_dic["quantity"][index],
        "price" : my_dic["price"][index]
        }

# Print out how it looks now
pprint.pprint(fruits)

# get your sorted list
fruit_names = sorted(my_dic["name"])

# and do the print out of the data
for name in fruit_names:
    print(f"\n{name}:")
    print(f"price: {fruits[name]['price']}")
    print(f"quantity: {fruits[name]['quantity']}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM