排序python字典列表
我有以下代码:排序python字典列表,python,Python,我有以下代码: from BeautifulSoup import BeautifulSoup TABLE_CONTENT = [['958','<a id="958F" href="javascript:c_row(\'958\')" title="go to map"><img src="/images/c_map.png" border="0"></a>','USA','Atmospheric','<a href="javascript:c_ol
from BeautifulSoup import BeautifulSoup
TABLE_CONTENT = [['958','<a id="958F" href="javascript:c_row(\'958\')" title="go to map"><img src="/images/c_map.png" border="0"></a>','USA','Atmospheric','<a href="javascript:c_ol(\'958\')" title="click date time to show origin_list (evid=958)">1945/07/16 11:29:45</a>','33.6753','-106.4747','','-.03','21','','','TRINITY',' ',' ','<a href="javascript:c_md(\'958\')" title="click here to show source data">SourceData</a>',' '],['959','<a id="959F" href="javascript:c_row(\'959\')" title="go to map"><img src="/images/c_map.png" border="0"></a>','USA','Atmospheric','<a href="javascript:c_ol(\'959\')" title="click date time to show origin_list (evid=959)">1945/08/05 23:16:02</a>','34.395','132.4538','','-.58','15','','','LITTLEBOY',' ',' ','<a href="javascript:c_md(\'959\')" title="click here to show source data">SourceData</a>',' ']]
EVENT_LIST = []
for EVENT in TABLE_CONTENT:
events = {}
for index, item in enumerate(EVENT):
if index == 0:
events['id'] = item
if index == 4:
soup = BeautifulSoup(item)
for a in soup.findAll('a'):
events['date'] = ''.join(a.findAll(text=True))
if index == 2:
events['country'] = item
if index == 3:
events['type'] = item
if index == 5:
events['lat'] = item
if index == 6:
events['lon'] = item
if index == 8:
events['depth'] = item
if index == 9:
events['yield'] = item
if index == 12:
events['name'] = item
sorted(events, key=lambda key: events['id'])
EVENT_LIST.append(events)
print '=== new record ==='
EVENT_LIST.sort(key=lambda x: x['id'])
print EVENT_LIST
还有没有更好的方法来编写此代码?
字典按定义是无序的,因为它们在内部存储为哈希表。缺少排序是从哈希表中插入和删除键的算法的结果。因此,您永远不应该依赖字典的键按任何特定顺序排列。也许可以考虑使用元组代替,或者一个字典列表——后者将允许您维护一个键:值格式,同时也保证一个可靠的排序。p> 如果你真的开始使用字典,你可能还想看看OrderedDict,尽管如果你使用dict并要求对其进行排序,你对数据的想法是错误的,可能有一种更简单的方法
对于好奇的人来说,这是一个很好的演示,它确切地解释了为什么Python字典有未定义的顺序您可以通过使用容器来保留插入字典的顺序。从手册中: 返回dict子类的实例,支持通常的dict 方法。OrderedDict是一种能够记住按键顺序的命令 第一次插入。如果新条目覆盖现有条目,则 原始插入位置保持不变。删除条目并 重新插入会将其移动到末端 此功能仅从2.7版开始使用 @更好的方法是:您可以将后续的
if index==…
更改为elif index==…
,因为如果索引是2,它永远不可能是5。或者,您可以存储索引/键组合,并使用它们来存储项目。示例(未尝试):
我想你明白了。默认情况下,Python中的字典是无序的
您可以使用。请注意,这仅在Python 2.7+中可用,更适合您的转换:
from BeautifulSoup import BeautifulSoup
HEADERS = ['id', None, 'country', 'type', 'date', 'lat', 'lon', None, 'depth', 'yield', None, None, 'name']
TABLE_CONTENT = [['958','<a id="958F" href="javascript:c_row(\'958\')" title="go to map"><img src="/images/c_map.png" border="0"></a>','USA','Atmospheric','<a href="javascript:c_ol(\'958\')" title="click date time to show origin_list (evid=958)">1945/07/16 11:29:45</a>','33.6753','-106.4747','','-.03','21','','','TRINITY',' ',' ','<a href="javascript:c_md(\'958\')" title="click here to show source data">SourceData</a>',' '],['959','<a id="959F" href="javascript:c_row(\'959\')" title="go to map"><img src="/images/c_map.png" border="0"></a>','USA','Atmospheric','<a href="javascript:c_ol(\'959\')" title="click date time to show origin_list (evid=959)">1945/08/05 23:16:02</a>','34.395','132.4538','','-.58','15','','','LITTLEBOY',' ',' ','<a href="javascript:c_md(\'959\')" title="click here to show source data">SourceData</a>',' ']]
EVENT_LIST = []
for EVENT in TABLE_CONTENT:
events = {}
for index, item in enumerate(EVENT):
if index != 4:
events[HEADERS[index]] = item
if index == 4:
soup = BeautifulSoup(item)
for a in soup.findAll('a'):
events[HEADERS[index]] = ''.join(a.findAll(text=True))
sorted(events, key=lambda key: events['id'])
EVENT_LIST.append(events)
print '=== new record ==='
EVENT_LIST.sort(key=lambda x: x['id'])
print EVENT_LIST
从美化组导入美化组
HEADERS=['id',None',country',type',date',lat',lon',None',depth',yield',None,None',name']
表U内容=['958'、'USA'、'Atmospheric'、'33.6753'、'106.4747'、'''-.03'、'21'、'''、'TRINITY'、''、''、''、''、''、''、''、''、'USA'、'Atmospheric'、''、'34.395'、'132.4538'、'-.58'、'15'、''、''、''、'LITTLEBOY'、''、''、''、''、''、''、''.']
事件列表=[]
对于表_内容中的事件:
事件={}
对于索引,枚举(事件)中的项:
如果索引!=4:
事件[标题[索引]]=项
如果索引=4:
汤=美汤(项目)
对于汤中的a.findAll('a'):
事件[标题[索引]]=''.join(a.findAll(text=True))
已排序(事件,key=lambda key:events['id'])
事件列表。附加(事件)
打印'===新记录==='
事件列表.sort(key=lambda x:x['id'])
打印事件列表
首先对您的代码进行一些评论:
events
?它只是一个事件
事件
变量?例如,如果事件的格式不正确(例如没有项),则可能很危险sorted
在代码中是不可操作的,它没有副作用dict
是基于哈希的。如果您确实需要保留订单,可以使用collections.OrderedDict
顺便说一下,这里有一个例子:
import operator
event_list = []
for event in TABLE_CONTENT:
event_dict = {}
event_dict['id'] = event[0]
event_dict['country'] = event[2]
# ...
event_dict['name'] = event[12]
event_list.append(event_dict)
event_list = sorted(event_list, key = operator.itemgetter('id'))
print event_list
可能是重复的,我实际上喜欢这个问题,因为你发布了一个关于dicts如何实际工作的奇妙链接。(+1). 唉。我希望我能喜欢一个答案……“因此,你永远不应该依赖字典的键按任何特定顺序排列。”好吧,除非你需要:
from BeautifulSoup import BeautifulSoup
HEADERS = ['id', None, 'country', 'type', 'date', 'lat', 'lon', None, 'depth', 'yield', None, None, 'name']
TABLE_CONTENT = [['958','<a id="958F" href="javascript:c_row(\'958\')" title="go to map"><img src="/images/c_map.png" border="0"></a>','USA','Atmospheric','<a href="javascript:c_ol(\'958\')" title="click date time to show origin_list (evid=958)">1945/07/16 11:29:45</a>','33.6753','-106.4747','','-.03','21','','','TRINITY',' ',' ','<a href="javascript:c_md(\'958\')" title="click here to show source data">SourceData</a>',' '],['959','<a id="959F" href="javascript:c_row(\'959\')" title="go to map"><img src="/images/c_map.png" border="0"></a>','USA','Atmospheric','<a href="javascript:c_ol(\'959\')" title="click date time to show origin_list (evid=959)">1945/08/05 23:16:02</a>','34.395','132.4538','','-.58','15','','','LITTLEBOY',' ',' ','<a href="javascript:c_md(\'959\')" title="click here to show source data">SourceData</a>',' ']]
EVENT_LIST = []
for EVENT in TABLE_CONTENT:
events = {}
for index, item in enumerate(EVENT):
if index != 4:
events[HEADERS[index]] = item
if index == 4:
soup = BeautifulSoup(item)
for a in soup.findAll('a'):
events[HEADERS[index]] = ''.join(a.findAll(text=True))
sorted(events, key=lambda key: events['id'])
EVENT_LIST.append(events)
print '=== new record ==='
EVENT_LIST.sort(key=lambda x: x['id'])
print EVENT_LIST
import operator
event_list = []
for event in TABLE_CONTENT:
event_dict = {}
event_dict['id'] = event[0]
event_dict['country'] = event[2]
# ...
event_dict['name'] = event[12]
event_list.append(event_dict)
event_list = sorted(event_list, key = operator.itemgetter('id'))
print event_list