[英]how to convert the list to dictionary where first list is key and second list is value in dictionary?
I was trying following question我正在尝试以下问题
I tried all my best but got stucked at the end part to convert the list to dictionary given in question above ie {1.3:[1.2,1.4]}
here is how i did my solution for above question.我尽我所能,但在最后部分被卡住了,将列表转换为上面给出的字典,即
{1.3:[1.2,1.4]}
这是我如何解决上述问题的方法。
lst=[]
l=[1.3]
k=[1.2,1.4,1.5,1.6,2.3,3.4,3.6,3.8,4.2,5.4,5.8]
for x in range(len(l)):
for z in range(len(k)):
b=k[z]-l[x]
if b>0.1:
l.append(k[z])
elif b<=0.1:
print(lst.append(k[z]))
print(lst)
print(l)
how can I convert the list to dictionary at the end?最后如何将列表转换为字典? ie {1.3:[1.2,1.4]}
即 {1.3:[1.2,1.4]}
Check this,检查这个,
lst=dict() # create an empty dictionary
l=[1.3]
k=[1.2,1.4,1.5,1.6,2.3,3.4,3.6,3.8,4.2,5.4,5.8]
for x in range(len(l)):
lst[str(l[x])] = [] # create a new dict entry with a key from l and an empty list
for z in range(len(k)):
b=k[z]-l[x]
if b>0.1:
l.append(k[z])
elif b<=0.1:
print(lst[str(l[x])].append(k[z])) # add to the empty list inside the dictionary of corresponding entry in l that you are checking with
print(lst)
print(l)
{'1.3': [1.2, 1.4]}
[1.3, 1.5, 1.6, 2.3, 3.4, 3.6, 3.8, 4.2, 5.4, 5.8]
I finally used fromkey()
method and it solved my question我终于使用了
fromkey()
方法,它解决了我的问题
new_dict=[]
compare_value = 0.1
list_main=[1.3]
test_set=[1.2,1.4,1.5,1.7,2.3,3.4,3.6,3.8,4.2,5.4,5.8]
for x in range(len(list_main)):
for z in range(len(test_set)):
diff=test_set[z]-list_main[x]
if diff>compare_value:
list_main.append(test_set[z])
elif diff<=compare_value:
new_dict.append(test_set[z])
dictionary=dict.fromkeys(list_main, new_dict)
print('dictionary----',dictionary)
print('list-------',list_main)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.