2016-03-16 254 views
3

比方说,我与这段文字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]} 
+0

请修复缩进 – flaschbier

回答

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 
+0

请注意,由于这是Python3,'map'会返回一个迭代器,而不是一个列表。如果你想要列表,你可能需要将'map'包装在'list'语句中,即'list(map(int,.. etcc))' –

+0

好点,我只在python2中检查过代码。谢谢你,解决了这个问题.. –

1

您需要通过拆分此字典值”, “然后将其映射到int:

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

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

  • 分裂的逗号split(',')
  • 的字符串转换成整数int(i)

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

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

是的,@SvenMarnach谢谢你的提示。 –

2

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

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

非常好。我喜欢这种方法。 – Sandeep