在Python中将列表更改为字典

时间:2018-08-26 06:51:13

标签: python dictionary

嗨,我有一个清单:

lst = ['Bedroom,24', 'Bedroom,26', 'Kitchen,22', 'Kitchen,23', 'Living Room,23', 'Living Room,24', 'Living Room,25']

现在我想不出办法将其更改为字典:

lst = {'temp':24,.....}

我尝试替换逗号,但由于列出了逗号,因此无法解决。我用过循环,但似乎没用,加上我是一个初学者,我也不知道如何将数字更改为整数。以下示例列出了该列表:

fname = open("temps1.txt")     
lst = []    

for line in fname:
  line = line.rstrip()      
  words = line.splitlines() 

    for word in words:
    if word in lst: continue
    lst = lst + words     
  lst.sort() 
print(lst)

>>>>>>['temp,24', 'bedroom,26', 'class,23'] #output

最后,是否可以将列表隐藏到字典中?
我的输出应该是:

 Average temp:
 bedroom: #value
 living room:#value

以此类推

2 个答案:

答案 0 :(得分:0)

您应该遍历列表,然后使用逗号将其分开。 您可以执行以下操作。

lst = ['temp,24','bedroom,26','class,23']

dict_obj = dict()
for element in lst:
    dict_obj[element.split(',')[0]] = int(element.split(',')[1])

print(dict_obj)

更新 由于OP的要求是查找数据的平均值,因此方法会发生变化

lst = ['Bedroom,24', 'Bedroom,26', 'Kitchen,22', 'Kitchen,23', 'Living Room,23', 'Living Room,24', 'Living Room,25']

dict_obj = dict()
for element in lst:
    if element.split(',')[0] in dict_obj:
        dict_obj[element.split(',')[0]]['temperature_reading'].append(int(element.split(',')[1]))
        dict_obj[element.split(',')[0]]['average_temperature'] = sum(dict_obj[element.split(',')[0]]['temperature_reading']) / len(dict_obj[element.split(',')[0]]['temperature_reading'])
    else:
        dict_obj[element.split(',')[0]] = {'temperature_reading' : [int(element.split(',')[1])],
                                           'average_temperature' : element.split(',')[1]}

print(dict_obj)

输出:

{
    'Bedroom': {'average_temperature': 25.0, 'temperature_reading': [24, 26]},
    'Kitchen': {'average_temperature': 22.5, 'temperature_reading': [22, 23]},
    'Living Room': {'average_temperature': 24.0,
                 'temperature_reading': [23, 24, 25]}
}

答案 1 :(得分:0)

最简单的方法:

print(dict([(i.split(',')[0],int(i.split(',')[1])) for i in lst]))

输出:

{'temp': 24, 'bedroom': 26, 'class': 23}