简体   繁体   中英

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.

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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