Name = []
Address = []
for a in range(1):
Name = raw_input ('Enter Name: ')
Address = raw_input ('Enter Address: ')
print Name
print Address
print [dict(zip(Name, e)) for e in Address]
a +=1
这就是我得到的
Enter Name: Kapil
Enter Address: Soni
Kapil
Soni
[{'K': 'S'}, {'K': 'o'}, {'K': 'n'}, {'K': 'i'}]
我想创建如下
{'Kapil':'Soni'}
我做错了什么?
答案 0 :(得分:5)
您使用相同的名称列表和输入变量来保存单个名称。试试这个:
name_address_pairs = []
for a in range(1):
name = raw_input ('Enter Name: ')
address = raw_input ('Enter Address: ')
print name
print address
name_address_pairs.append( { name: address } )
(作为旁注,变量名应按惯例以小写字母开头。)
答案 1 :(得分:4)
addressbook = {}
for a in range(1):
name = raw_input ('Enter Name: ')
address = raw_input ('Enter Adress: ')
addressbook[name] = address
print addressbook
names = []
addresses = []
for a in range(1):
name = raw_input ('Enter Name: ')
address = raw_input ('Enter Adress: ')
names.append(name)
addresses.append(address)
print dict(zip(names, addresses))
答案 2 :(得分:0)
您正在定义Name = []
,然后分配Name = input()
,将数据类型更改为字符串。
此外,压缩字符串会将字符串转换为列表。例如
print zip('foo','bar')
# will produce
[('f', 'b'), ('o', 'a'), ('o', 'r')]
您想要做的只是
# in the beginning
address_book = []
# and in your loop
print { Name : Address }
address_book[ Name ] = Address
答案 3 :(得分:0)
有一种简单的方法可以做到这一点:
print "{",Name,":",Address,"}"
如果要将收到的所有输入添加到单个词典中,请执行以下操作:
dictionary={}
for a in range(20):
Name=raw_input()
Address=raw_input()
dictionary[Name]=Address