繁体   English   中英

如何将列表转换为字典,其中第一个列表是键,第二个列表是字典中的值?

[英]how to convert the list to dictionary where first list is key and second list is value in dictionary?

我正在尝试以下问题

我尽我所能,但在最后部分被卡住了,将列表转换为上面给出的字典,即{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)

最后如何将列表转换为字典? 即 {1.3:[1.2,1.4]}

检查这个,

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]

我终于使用了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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM