关于python:将字典的值转换为列表?

Convert value of dictionary as a list?

本问题已经有最佳答案,请猛点这里访问。

比如说,我收到了这篇文章age_gender.txt

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

这是我到目前为止的密码

1
2
3
4
5
file = open("age_gender.txt")
   contents = file.read().splitlines()
   new_dictionary = dict(item.split(":") for item in contents)

return new_dictionary

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

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

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

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


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

1
2
3
4
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)}

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

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

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

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

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


你已经完成了基本步骤,剩下的步骤是:

  • 拆分逗号EDOCX1的值〔0〕。
  • 将字符串转换为整数int(i)

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

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


1
2
3
4
5
6
7
8
9
>>> 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]}

将其应用于代码:

1
2
3
4
5
6
7
8
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


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

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