将python列表放入dict [英] python list into dict
本文介绍了将python列表放入dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的问题.
我有一个这样的列表(在我已经分配给列表元素的.txt文件中):
I have a list like this (out of a .txt file I have already assigned to a list element):
sharenames = ['VIAB:Viacom Inc.', 'DLTR:Dollar Tree Inc.', 'AAL:American Airlines Group Inc.', 'ROST:Ross Stores Inc.', 'VRTX:Vertex Pharmaceuticals Incorporated', 'WDC:Western Digital Corp', 'NCLH:Norwegian Cruise Line Holdings Ltd', 'SWKS:Skyworks Solutions Inc.', 'BBBY:Bed Bath & Beyond Inc.', 'BIDU:Baidu Inc (ADR)', 'ENDP:Endo International plc', '"FRA:DBK":Deutsche Bank AG', '"FRA:FME":Fresenius Medical Care AG & Co. KGaA', '"FRA:DAI":Daimler AG']
我想创建一个我可以访问访问权限的字典
I want to create a dictionary I can access access like
wertA = sharenames["FRA:FME"] # as an example
或
wertA = sharenames[ROST] # as an example
经过数小时的尝试和错误,希望您能为我提供帮助.
After some hours of try and error I hope you can help me out.
推荐答案
您可以从元组列表创建映射:
You can create a mapping from a list of tuples:
data = ['VIAB:Viacom Inc.', 'DLTR:Dollar Tree Inc.', 'AAL:American Airlines Group Inc.', 'ROST:Ross Stores Inc.', 'VRTX:Vertex Pharmaceuticals Incorporated', 'WDC:Western Digital Corp', 'NCLH:Norwegian Cruise Line Holdings Ltd', 'SWKS:Skyworks Solutions Inc.', 'BBBY:Bed Bath & Beyond Inc.', 'BIDU:Baidu Inc (ADR)', 'ENDP:Endo International plc', '"FRA:DBK":Deutsche Bank AG', '"FRA:FME":Fresenius Medical Care AG & Co. KGaA', '"FRA:DAI":Daimler AG']
mapping = dict(entry.rsplit(':', 1) for entry in data)
注意,我正在最大程度地使用string.rsplit
进行单个拆分(第二个参数).另外,这假设您的值中没有冒号.
Notice I'm using string.rsplit
to the maximum of a single split (second argument). Also, this assumes you have no colons in your values.
映射项:
ENDP -> Endo International plc
WDC -> Western Digital Corp
VIAB -> Viacom Inc.
AAL -> American Airlines Group Inc.
DLTR -> Dollar Tree Inc.
BBBY -> Bed Bath & Beyond Inc.
"FRA:DAI" -> Daimler AG
VRTX -> Vertex Pharmaceuticals Incorporated
"FRA:FME" -> Fresenius Medical Care AG & Co. KGaA
SWKS -> Skyworks Solutions Inc.
NCLH -> Norwegian Cruise Line Holdings Ltd
ROST -> Ross Stores Inc.
"FRA:DBK" -> Deutsche Bank AG
BIDU -> Baidu Inc (ADR)
要清除双引号中的键,您可以执行以下操作:
To clean keys from double-quotes you can do:
clean_mapping = {k.replace('"',''): v for k, v in mapping}
这篇关于将python列表放入dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文