在字典python中转换列表列表 [英] Converting list of lists in dictionary python
本文介绍了在字典python中转换列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正面临以下问题.我有一个使用以下代码从远程URL获取的列表列表:
I'm facing the following problem. I have a list of lists obtained from a remote URL with the following code:
import csv
import urllib.request
text_url = 'https://www.emidius.eu/fdsnws/event/1/query?starttime=1899-01-01T00:00:00&endtime=1899-01-31T23:59:59&minmag=4&maxmag=9&orderby=time-asc&limit=100&format=text'
with urllib.request.urlopen(text_url) as response:
my_text = response.read().decode()
lines = my_text.splitlines()
reader = csv.reader(lines, delimiter='|')
我可以使用以下方法将阅读器转换为列表列表:
I can convert the reader as a list of lists with:
my_list = list(reader)
我想做的就是在列表字典中转换列表列表(或在 reader
本身内).第一个列表的项应成为字典键,而从第二个元素到最后一个元素,我希望将字典值作为列表获取:
What I'm trying to do is converting the list of lists (or within the reader
itself) in a dictionary of lists. The items of the first list should become the dictionary keys while, from the second to the last element, I'd like to get the dictionary values as a list:
my_list[0] # dict keys
['#EventID',
'Time',
'Latitude',
'Longitude',
'Depth/km',
'Author',
'Catalog',
'Contributor',
'ContributorID',
'MagType',
'Magnitude',
'MagAuthor',
'EventLocationName']
my_list[1:] # dict values as list
[['quakeml:eu.ahead/event/18990105_0245_000',
'1899-01-05T02:45:--',
'41.500',
'13.783',
'',
'AHEAD',
'SHEEC',
'CPTI04',
'1309',
'Mw',
'4.63',
'SHEEC',
'Pignataro'],
['quakeml:eu.ahead/event/18990118_2048_000',
'1899-01-18T20:48:--',
'46.180',
'14.500',
'4.8',
'AHEAD',
'SHEEC',
'RIBA982',
'',
'Mw',
'4.51',
'SHEEC',
'Vodice Brnik'],
['quakeml:eu.ahead/event/18990122_0956_000',
'1899-01-22T09:56:--',
'37.200',
'21.600',
'',
'AHEAD',
'SHEEC',
'PAPA003',
'',
'Mw',
'6.50',
'SHEEC',
'Kyparissia'],
['quakeml:eu.ahead/event/18990131_1112_000',
'1899-01-31T11:12:--',
'66.300',
'-19.900',
'',
'AHEAD',
'SHEEC',
'AMBSI000',
'',
'Mw',
'5.80',
'SHEEC',
'[N. Iceland]'],
['quakeml:eu.ahead/event/18990131_2345_000',
'1899-01-31T23:45:--',
'60.100',
'5.500',
'30',
'AHEAD',
'SHEEC',
'FEN007',
'',
'Mw',
'4.60',
'SHEEC',
'[Biornafjorden]']]
基本上,输出应类似于:
Basically the output should be something like:
d['#EventID'] = ['quakeml:eu.ahead/event/18990105_0245_000', 'quakeml:eu.ahead/event/18990105_0245_000', 'quakeml:eu.ahead/event/18990105_0245_000']
推荐答案
使用 csv.DictReader
和 dict.setdefault
例如:
import csv
d = {}
reader = csv.DictReader(lines, delimiter='|')
for row in reader: #Iterate Each row
for k, v in row.items(): #Iterate Key-Value
d.setdefault(k, []).append(v)
这篇关于在字典python中转换列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文