有没有办法向字典添加列表?蟒蛇

时间:2016-12-09 09:40:27

标签: python list dictionary

我对编程相对较新,对这个网站来说是全新的,所以我只是想到了我一直试图找出最后一小时答案的问题。

我想将项目添加到两个列表中,然后将这些列表放入字典中以存储并最终输出。

我提出了两种不同的解决方案,但它们都不起作用:

使用馆藏模块:

import collections
Cnum = 5
print("We will now be asking you to enter the names and age of the individual people coming. ")
details = {}
count = 0
Cnam = []
Cage = []
while count < Cnum:
    Cnam.append( raw_input('Please enter the name of a citizen: '))
    Cage.append(int(raw_input('Please enter the age of this citizen: ')))
    d = collections.defaultdict(list)
    d[Cname].append(Cage)
    count = count + 1
print details

没有:

Cnum = 5
details = {}
count = 0
Cnam = []
Cage = []
while count < Cnum
    Cnam.append(raw_input('Please enter the name of a citizen: '))
    Cage.append(int(raw_input('Please enter the age of this citizen: ')))
    details[Cnam] = Cage
    count = count + 1
print details

真的很感激任何帮助。如果无法向词典添加列表,那么任何其他想法也将受到赞赏。

2 个答案:

答案 0 :(得分:0)

我认为你试图设置为字典的键不可用类型'列表'的问题。你不能做这个。 尝试使用元组代替:

details[tuple(Cnam)] = Cage

所以你可以这样做:

Cnum = 5
details1 = {}
details2 = {}
count = 0
Cnam = []
Cage = []
while count < Cnum:
    name = raw_input('Please enter the name of a citizen: ')
    Cnam.append(name)
    age = int(raw_input('Please enter the age of this citizen: '))
    Cage.append(age)
    details1[name] = age
    count = count + 1
details2[tuple(Cnam)] = Cage
print('Cnam: {}'.format(Cnam))
print('Cage: {}'.format(Cage))
print('details1: {}'.format(details1))
print('details2: {}'.format(details2))

输出:

Cnam: ['q', 'w', 'e', 'r', 't']
Cage: [1, 2, 3, 4, 5]
details1: {'q': 1, 'r': 4, 'e': 3, 't': 5, 'w': 2}
details2: {('q', 'w', 'e', 'r', 't'): [1, 2, 3, 4, 5]}

答案 1 :(得分:0)

如果您确实需要CnamCage列表,那么简单的方法是创建列表,然后使用内置{{1}将它们传递给dict构造函数功能。

zip

<强>测试

Cnum = 5
Cnam = []
Cage = []
for count in range(Cnum):
    Cnam.append(raw_input('Please enter the name of a citizen: '))
    Cage.append(int(raw_input('Please enter the age of this citizen: ')))

print Cnam
print Cage
details = dict(zip(Cnam, Cage))
print details

如果您不需要这些列表,我们可以使代码更简单:

Please enter the name of a citizen: a
Please enter the age of this citizen: 1
Please enter the name of a citizen: b
Please enter the age of this citizen: 2
Please enter the name of a citizen: c
Please enter the age of this citizen: 3
Please enter the name of a citizen: d
Please enter the age of this citizen: 4
Please enter the name of a citizen: e
Please enter the age of this citizen: 5
['a', 'b', 'c', 'd', 'e']
[1, 2, 3, 4, 5]
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}