如何按字典值对其排序

时间:2019-06-27 02:56:22

标签: python python-3.x pandas tkinter

我正在处理excel文件,以在新的tkinter窗口上显示数据。我想使用“代理”列值对行进行排序,然后在tkinter窗口上将其显示

我尝试使用条件和迭代,但是我做不到。

以下是数据:

  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

代码如下:

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

输出:

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

预期输出:

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

2 个答案:

答案 0 :(得分:0)

for key, value in sorted(mydict.items(), key=lambda item: item[1]):
    print("%s: %s" % (key, value))

如果要按值对它进行排序,这可能会有所帮助。它将按键及其值排序,并且将在整个字典中进行迭代。从理论上讲,它可能会起作用。 PS:还没有测试

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

答案 1 :(得分:0)

您不需要第二个循环。

使用:

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

输出:

Sam
Japan FOB - (2915660.0)
Dave
Japan FOB - (3180720.0)
相关问题