将字典值转换为列表?

时间:2016-03-16 22:44:44

标签: python python-3.x

假设我收到了此文age_gender.txt

Female:18,36,35,49,19
Male:23,22,26,26,26

这是我到目前为止的代码

file = open("age_gender.txt")
   contents = file.read().splitlines()
   new_dictionary = dict(item.split(":") for item in contents)

return new_dictionary

当我调用函数readfile()时,这是我得到的输出,但值列表仍然是引号。如何将每个值转换为列表?

{'Female': '18,36,35,49,19', 'Male': '23,22,26,26,26'}

我想要实现的输出是这样的

{'Female': [18,36,35,49,19], 'Male': [23,22,26,26,26]}

4 个答案:

答案 0 :(得分:2)

>>> a
'Female:18,36,35,49,19,19,40,23,22,22,23,18,36,35,49,19,19,18,36,18,36,35,12,19,19,18,23,22,22,23'
>>> a.split(':')
['Female', '18,36,35,49,19,19,40,23,22,22,23,18,36,35,49,19,19,18,36,18,36,35,12,19,19,18,23,22,22,23']
>>> a.split(':')[1].split(',')
['18', '36', '35', '49', '19', '19', '40', '23', '22', '22', '23', '18', '36', '35', '49', '19', '19', '18', '36', '18', '36', '35', '12', '19', '19', '18', '23', '22', '22', '23']
>>> new_dictionary = dict({a.split(':')[0]:map(int,a.split(':')[1].split(','))}) 
>>> new_dictionary
{'Female': [18, 36, 35, 49, 19, 19, 40, 23, 22, 22, 23, 18, 36, 35, 49, 19, 19, 18, 36, 18, 36, 35, 12, 19, 19, 18, 23, 22, 22, 23]}

将其应用于您的代码:

file = open("age_gender.txt")
   contents = file.read().splitlines()
   new_dictionary = dict()
   for item in contents:
       tmp = item.split(':')
       new_dictionary[tmp[0]] = list(map(int, tmp[1].split(',')))

return new_dictionary

答案 1 :(得分:2)

你已经完成了基础知识,剩下的步骤是:

  • 在逗号split(',')
  • 上拆分值
  • 将字符串转换为整数int(i)

for循环中包装这些步骤,并为字典的每个键/值对执行此操作。

for key, value in new_dictionary.items():
    new_dictionary[key] = [int(i) for i in value.split(',')]

答案 2 :(得分:2)

这是使用ast.literal_eval将年龄转换为Python列表的另一种方法。它具有支持所有基本数据类型的优点,例如, float,没有显式转换:

from ast import literal_eval

with open('age_gender.txt') as f:
    d = {gender: literal_eval(ages) for gender, ages in (line.split(':') for line in f)}

这将生成一个以元组为值的字典:

{'Male': (23, 22, 26, 26, 26), 'Female': (18, 36, 35, 49, 19)}

如果你确实需要列表,你可以转换元组:

with open('age_gender.txt') as f:
    d = {gender: list(literal_eval(ages)) for gender, ages in (line.split(':') for line in f)}
{'Male': [23, 22, 26, 26, 26], 'Female': [18, 36, 35, 49, 19]}

答案 3 :(得分:1)

您需要将此字典值拆分为","然后将其映射到int:

s['Female'] = map(int, s['Female'].split(','))