[英]How to create a dictionary from a list of tuples without overwriting the keys
I have a script that extracts files from a website, the key across the files are the same.我有一个从网站提取文件的脚本,文件中的密钥是相同的。
I want to create a dictionary from these files extracted files without overwriting the keys.我想从这些文件中提取文件创建一个字典而不覆盖键。
table_information = []
for t in my_url[:5]:
page_detail = requests.get(t)
tree_1 = html.fromstring(page_detail.content)
title = ''.join(tree_1.xpath('//div/h1[@class="title"]/text()'))
Track = title.split(' ')[0].strip()
date = title.split('-')[1].strip()
year = pd.to_datetime('now').year
race_date = pd.to_datetime(date + ' ' + str(year)).strftime('%d/%m/%Y')
table_information.append((race_date,Track))
The above code extracts the files and appends them to a list.上面的代码提取文件并将它们附加到列表中。
The extracted files are like this.提取出来的文件是这样的。
table_information =
[('Angle', '01/10/2021', ['342m', '342m', '530m', '342m', '342m', '595m', '530m', '342m', '342m', '342m']),
('Ballarat', '02/10/2021', ['390m', '390m', '390m', '390m', '450m', '450m', '450m', '450m', '390m', '390m']),
('Bendigo', '02/10/2021', ['425m', '425m', '425m', '425m', '500m', '500m', '500m', '425m', '425m', '425m', '425m', '425m'])]
Now I want to a dictionary of this form.现在我想要一本这种形式的字典。
new_dict = { 'Date':['01/10/2021', '02/10/2021', '02/10/2021'],
'Track': ['Angle', 'Ballarat', 'Bendigo'],
'Distance': [['342m', '342m', '530m', '342m', '342m', '595m', '530m', '342m', '342m', '342m'],
['390m', '390m', '390m', '390m', '450m', '450m', '450m', '450m', '390m', '390m'],
['425m', '425m', '425m', '425m', '500m', '500m', '500m', '425m', '425m', '425m', '425m', '425m']]
}
I tried to create the dictionary using the below code, but I keys repeated multiple times.我尝试使用以下代码创建字典,但我重复了多次键。 Please how can I achieve this?.
请问我怎样才能做到这一点?
greyhound = {}
new_dict = {}
greyhoud['Date'] = [race_date]
greyhoud['Distatnce'] = [Distatnce]
greyhoud['Track'] = [Track]
for k,v in greyhoud.items():
for key in k:
if key in new_dict:
new_dict[k].append(v)
else:
new_dict[k] = [v]
Just loop through table_information
, appending each element in the tuples to the appropriate dictionary elements.只需遍历
table_information
,将元组中的每个元素附加到适当的字典元素。
greyhound = {'Date': [], 'Track': [], 'Distance': []}
for track, date, distance in table_information:
greyhound['Track'].append(track)
greyhound['Date'].append(date)
greyhound['Distance'].append(distance)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.