Reputation: 53
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:
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
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 thefind
function in dictionary if x in data.keys():
to check, no need to check x with k one by one.
Upvotes: 0
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
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