简体   繁体   English

如何按字典值对其排序

[英]How to sort dictionary by its values

I'm working on excel file to show the data on new tkinter window. 我正在处理excel文件,以在新的tkinter窗口上显示数据。 I want to sort the rows using the Agent column values and ditsplay it on tkinter window 我想使用代理列值对行进行排序,然后在tkinter窗口上对其进行播放

I tried using condition and iteration but i can't do it properly. 我尝试使用条件和迭代,但无法正确执行。

Here is the data: 数据如下:

  Country       Port incoterm Capacity    Date Agent  $ value      Total
0   Japan   Yokohama      FOB    20ton  2019/5   Sam   2650.6  2650600.0
1   China     Ningbo      DAT    40ton  2019/1    Li   2650.6  2385540.0
2     USA  Baltimore      FOB    Other  2018/9  John   2650.6  4240960.0
3  Russia     Moscow      EXW    20ton  2019/1  Vlad   2650.6  2120480.0
4   Japan      Tokyo      FOB    20ton  2019/1   Sam   2650.6  2915660.0
5   Japan      Tokyo      FOB    20ton  2019/1  Dave   2650.6  3180720.0
6   China   Shanghai      EXW    40ton  2019/1    Li   2500.6  3128250.6

Here is the code: 这是代码:

data = pd.read_excel("example.xlsx")
df = pd.DataFrame(data)
a = df.loc[(df.Country == 'Japan') & (df.incoterm == 'FOB') & (df.Capacity 
== '20ton') & (df.Port == 'Tokyo')]
_a = pd.DataFrame(a)
root = Tk()

for agent in _a.itertuples():
    if agent.Agent is agent.Agent:
        temp_agent = '{0}'.format(agent.Agent)
        ttk.Label(root, text="Agent:"+temp_agent).pack()
        for data in _a.itertuples():
            temp_text = '{0} {1} - ({2})'.format(data.Country, 
            data.incoterm, data.Total)
            ttk.Label(root, text=temp_text).pack()
            print (temp_text)
mainloop()

Output: 输出:

Sam
Japan FOB - (2915660.0)
Japan FOB - (3180720.0)
Dave
Japan FOB - (2915660.0)
Japan FOB - (3180720.0)

Expected output: 预期产量:

Sam
Japan FOB - (2915660.0)
Dave
Japan FOB - (3180720.0)

You do not need the second loop. 您不需要第二个循环。

Use: 采用:

_a = df.loc[(df.Country == 'Japan') & (df.incoterm == 'FOB') & (df.Capacity == '20ton') & (df.Port == 'Tokyo')]

for agent in _a.itertuples():
    if agent.Agent is agent.Agent:
        temp_agent = '{0}'.format(agent.Agent)
        print(temp_agent)
        temp_text = '{0} {1} - ({2})'.format(agent.Country, agent.incoterm, agent.Total)
        print (temp_text)

Output: 输出:

Sam
Japan FOB - (2915660.0)
Dave
Japan FOB - (3180720.0)
for key, value in sorted(mydict.items(), key=lambda item: item[1]):
    print("%s: %s" % (key, value))

if you want to sort it by value this might help. 如果您想按值对它进行排序,这可能会有所帮助。 it will be sorted by key and its value and it will iterate in whole dict. 它将按键及其值排序,并且将在整个字典中进行迭代。 in theory it might work. 从理论上讲,它可能会起作用。 PS: haven't test it yet PS:尚未测试

reference- https://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/ 参考-https://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/

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

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