Python dict1[d]=c只将列表2中的最后一项添加为字典中的值,我如何解决它?
当我输入“a,b,c,d”Python dict1[d]=c只将列表2中的最后一项添加为字典中的值,我如何解决它?,python,Python,当我输入“a,b,c,d” 输出是{'a':'d','b':'d'},我想要{'a':'c','b':'d'}问题在于循环逻辑: dict1 = {} list1 = [] list2 = [] x = input("Enter something: ").split(',') if len(x) % 2 == 1: b = input("please, add one more thing: ") x.append(b) for A in x[:len(x)//2]:
输出是{'a':'d','b':'d'},我想要{'a':'c','b':'d'}问题在于循环逻辑:
dict1 = {}
list1 = []
list2 = []
x = input("Enter something: ").split(',')
if len(x) % 2 == 1:
b = input("please, add one more thing: ")
x.append(b)
for A in x[:len(x)//2]:
list1.append(A)
for B in x[(len(x)//2):]:
list2.append(B)
for d in list1:
for c in list2:
dict1[d] = c
print(dict1)
内部循环重复重写dict1[d];只获得最后一个元素。我认为您需要的是从两个列表中排序成对
for d in list1:
for c in list2:
dict1[d] = c
了解你想要实现的目标会有所帮助;这似乎是一种非常不舒服的建立目录的方式
没有邮政编码,自己通信:
for d, c in zip(list1, list2):
dict1[d] = c
在这种情况下可以使用zip()函数
for i in range(len(list1)):
dict1[list1[i]] = list2[i]
这里不需要初始化,只需使用
dict
和zip
将列表切成两半即可
dict1 = {}
list1 = []
list2 = []
x = input("Enter something: ").split(',')
if len(x) % 2 == 1:
b = input("please, add one more thing: ")
x.append(b)
for A in x[:len(x)//2]:
list1.append(A)
for B in x[(len(x)//2):]:
list2.append(B)
for ele in zip(list1, list2):
dict1[ele[0]] = ele[1]
print dict1
谢谢,但我还没学会拉拉链。还有别的办法吗?哦,那更好谢谢!我还没有学会Zip,我的讲师不会接受的。一个人已经回答了我的问题。谢谢
x = input("Enter something: ").split(',')
if len(x) % 2 == 1:
b = input("please, add one more thing: ")
x.append(b)
h = len(x)//2
dict1 = dict(zip(x[:h], x[h:]))