gollyimgully
gollyimgully

Reputation: 53

How can I find matching items between a dictionary and a list to create a new list from the matches?

I have two sets of data - a dictionary (data) and a list (list_1) both of unequal lengths. I would like to iterate through both and do the following:

  1. If the item in list_1 matches the key data add the value to a 2nd list.
  2. If the item is not in the dictionary add "NULL" instead

Th 3rd list should be the same length as list_1

Here is the sample code:

a = ['dim','john','joey','tron','bob','wilt','kobe']
b = [1,2,3,4,5,6,7]
data = dict(zip(a,b))

list_1 = ['bob','sue','mike','willy','john','may','beth','wilt']

list_2 = []

for x in list_1:
    for key,value in data.items():
        if x in key:
            list_2.append(key)
        elif x not in key:
            list_2.append("NULL")

The results of this would be

['NULL', 'NULL', 'NULL', 'NULL', 'bob', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'john', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'wilt', 'NULL']

Is it possible to make the 3rd list show as the following?

['bob','NULL','NULL','NULL','john','NULL','NULL','wilt']

Upvotes: 2

Views: 53

Answers (3)

Juliecodestack
Juliecodestack

Reputation: 9

If you check the length of your output by using function len(), you would get 56=length_of_list1(8)*length_of_data(7). But you only need list 2 the same length of list1, so you may see that the loop for key,value in data.items():is redundant. You may use thefindfunction in dictionary if x in data.keys():to check, no need to check x with k one by one.

Upvotes: 0

enzo
enzo

Reputation: 11486

Just scroll through the list once.

for x in list_1:
    if x in list(data.keys()):
        list_2.append(x)
    else:
        list_2.append('NULL')

Upvotes: 1

Chris Mueller
Chris Mueller

Reputation: 6680

You can do this by simply checking if the value is in the keys of the dictionary.

list_1 = ['bob','sue','mike','willy','john','may','beth','wilt']
list_2 = []

for x in list_1:
    if x in data.keys():
        list_2.append(x)
    else:
        list_2.append("NULL")

If you want to be fancy and concise, you can use a list comprehension.

list_2 = [x if x in data.keys() else "NULL" for x in list_1]

Upvotes: 2

Related Questions