[英]How to sort dictionary by its values
我正在处理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)
您不需要第二个循环。
采用:
_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)
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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.