将字典值从元组转换为列表(Python)

时间:2018-11-29 20:50:33

标签: python list dictionary tuples

所以我有一个data.txt文件,其中包含有关汽车的信息:

  

CAR | PRICE | RPM

     

丰田| 21,000 | 3,600

     

本田| 19,000 | 4,000

然后通过将该数据文件传递到函数createCarDictionary中,我可以创建一个字典,该字典创建汽车品牌作为键,并将值作为存储在元组中的txt文件中的剩余信息:

dict1 = {}

def createCarDictionary(datafile):
    for line in datafile.splitlines():
        key, value, value2 = map(str.strip, line.split('|'))
        dict1[key] = value, value2
    return dict1

datafile = open('data.txt', 'r').read()

createCarDictionary(datafile)
print(dict1)

输出

{'CAR': ('PRICE', 'RPM'), 'TOYOTA': ('21,000', '3,600'), 'HONDA': ('19,000', '4,000')}

所以我的问题是: 我必须在函数中添加什么以 1) 删除数字中的逗号,然后 2) 转换元组值放入列表中,以便稍后使用。

2 个答案:

答案 0 :(得分:0)

您可以简单地用括号将值括起来,使它们成为list而不是tuple,并使用replace()删除每一行中的所有','。

dict1 = {}

def createCarDictionary(datafile):
    for line in datafile.splitlines():
        line = line.replace(',', '')
        key, value, value2 = map(str.strip, line.split('|'))
        dict1[key] = [value, value2]
    return dict1

datafile = open('data.txt', 'r').read()

createCarDictionary(datafile)
print(dict1)

输出:

{'HONDA': ['19000', '4000'], 'TOYOTA': ['21000', '3600'], 'CAR': ['PRICE', 'RPM']}

答案 1 :(得分:0)

一种方法,更改:

dict1[key] = value, value2

收件人:

dict1[key] = [int(i.replace(',','')) for i in (value1,value2)]


但是,如果您对新库开放的话,也可以使用 pandas

import pandas as pd

filedata = '''\
CAR|PRICE|RPM
TOYOTA|21,000|3,600
HONDA|19,000|4,000'''

fileobj = pd.compat.StringIO(filedata) # change this to the path of your file
df = pd.read_csv(fileobj, sep='|', thousands=',')
d = dict(zip(df.pop('CAR'), df.values.tolist()))
#d = df.set_index('CAR').to_dict('i') # OR MAYBE THIS?
print(d)

返回:

{'TOYOTA': [21000, 3600], 'HONDA': [19000, 4000]}