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

2024-09-15 17:47:38 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个data.txt文件,它保存了关于汽车的信息:

CAR|PRICE|RPM

TOYOTA|21,000|3,600

HONDA|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')}

所以我的问题是: 我必须向函数中添加什么,以删除数字中的逗号,并将元组值转换为列表,以便以后进行操作。你知道吗


Tags: 文件函数txt信息datalinecarprice
2条回答

单向,改变:

dict1[key] = value, value2

收件人:

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


但如果您对新库持开放态度,也可以使用熊猫:

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]}

您可以简单地用括号将值括起来,使它们成为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']}

相关问题 更多 >