0
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

This is what i am getting

Enter Name: Kapil
Enter Address: Soni
Kapil
Soni
[{'K': 'S'}, {'K': 'o'}, {'K': 'n'}, {'K': 'i'}]

i want to create as below

{'Kapil':'Soni'}

what wrong am i doing?

4

4 回答 4

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 } )

(附带说明一下,按照惯例,变量名称应以小写字母开头。)

于 2013-06-13T15:53:45.757 回答
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))
于 2013-06-13T15:54:37.573 回答
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
于 2013-06-13T15:55:00.653 回答
0

有一种简单的方法可以做到这一点:

print "{",Name,":",Address,"}"

如果要将收到的所有输入添加到单个字典中,请执行以下操作:

dictionary={}
for a in range(20):
    Name=raw_input()
    Address=raw_input()
    dictionary[Name]=Address
于 2013-06-13T15:55:37.453 回答