Lakhwinder Smagh
Lakhwinder Smagh

Reputation: 15

Comparing Python list values to dictionary keys

I am trying to create a new list by comparing the list items to dictionary keys, if the match is found then i append a value of dictionary to new list that was globally initialized. the code i am trying is as below

dict_1 = {'OMSS': '10.1.1.0/24', 'A&A': '10.1.2.0/24', 'AFM': '10.1.3.0/24', 'ATM': '10.1.4.0/24'}
list_1 = ['A&A', 'A&A', 'OMSS', 'OMSS', 'A&A', 'AFM', 'A&A', 'AFM', 'A&A']
list_2 = ['OMSS ', 'OMSS ', 'A&A ', 'A&A ', 'AFM ', 'A&A ', 'AFM ', 'A&A ', 'AFM ']

list_of_list1 = []

for s1 in list_1:
    #print (s2)
    for key, value in dict_1.items():
        #print (key)
        if s1 == key:
            list_of_list1.append(value)

print (list_of_list1)

list_of_list2 = []

for s2 in list_2:
    #print (s2)
    for key, value in dict_1.items():
        #print (key)
        if s2 == key:
            list_of_list2.append(value)

print (list_of_list2)

when i run this i get below output

['10.1.2.0/24', '10.1.2.0/24', '10.1.1.0/24', '10.1.1.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24']
{'OMSS': '10.1.1.0/24', 'A&A': '10.1.2.0/24', 'AFM': '10.1.3.0/24', 'ATM': '10.1.4.0/24'}
[]

i am trying to figure out why "list_of_list2" is coming out as empty?

Upvotes: 0

Views: 89

Answers (2)

madbird
madbird

Reputation: 1379

  1. Please stop using containers in most inefficient way. Just use list comprehension:
list_of_list1 = [dict_1[k] for k in list_1 if k in dict_1]
  1. All items of list_2 have ' ' at the end. Indeed they won't be equal to the keys you have in dict_1. Try to strip redundant spaces:
list_of_list2 = [dict_1[k.strip()] for k in list_2 if k.strip() in dict_1]

Upvotes: 1

biqarboy
biqarboy

Reputation: 852

You need to remove leading and tailing space from the list_2 items to be matched with the dictionary keys. Here is the sample fix of your problem:

dict_1 = {'OMSS': '10.1.1.0/24', 'A&A': '10.1.2.0/24', 'AFM': '10.1.3.0/24', 'ATM': '10.1.4.0/24'}
list_1 = ['A&A', 'A&A', 'OMSS', 'OMSS', 'A&A', 'AFM', 'A&A', 'AFM', 'A&A']
list_2 = ['OMSS ', 'OMSS ', 'A&A ', 'A&A ', 'AFM ', 'A&A ', 'AFM ', 'A&A ', 'AFM ']

list_of_list1 = []

for s1 in list_1:
    #print (s2)
    for key, value in dict_1.items():
        #print (key)
        if s1 == key:
            list_of_list1.append(value)

print (list_of_list1)

list_of_list2 = []

for s2 in list_2:
    #print (s2)
    for key, value in dict_1.items():
        #print (key)
        if s2.strip() == key:
            list_of_list2.append(value)

print (list_of_list2)

Output:

['10.1.2.0/24', '10.1.2.0/24', '10.1.1.0/24', '10.1.1.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24']
['10.1.1.0/24', '10.1.1.0/24', '10.1.2.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24', '10.1.3.0/24']

Upvotes: 0

Related Questions