# Dictionary comprehension with nested for loop and conditional if [closed]

Let's suppose I have two lists:

list_b = ['cat.2','dog.6','bear.10','zebra.13']
list_a = ['cat','dog','bear','zebra']


I would like to create a dictionary with the desired output:

dict_ = {'cat.2':'cat','dog.6':'dog','bear':'bear.10','zebra.13':'zebra'}


I have two possible solutions. I am assuming the lists are not ordered so I cannot simply do a dict(zip(list_a,list_b)) or something along those lines.

Solution 1:

dict_ = {}
for i in list_a:
for j in list_b:
if i.startswith(j):
dict_[i] = j


Solution 2:

dict_ = {key:value for key in list_a for value in list_b if key.startswith(value)}


I prefer solution two because, if I recall correctly, comprehensions should be much faster, but I do not know if there is a more efficient way of doing this.

• Hey, welcome to Code Review! Here we take a look at complete and working code and try to make it better. For this it is paramount to see the code in its actual environment. The more code you can show, the better. Hypothetical code, code stubs without context or general best practice questions are off-topic here. Have a look at our help center for more information. – Graipher Sep 18 '19 at 17:30
• I think the context is clear, even if implicit: "for each key in list_b, split on '.' and find the corresponding partial-match from list_a and use it as the value". Don't even need regex. Now if you mean the question is toy, that's different... – smci Sep 18 '19 at 22:52
• As @Reinderien showed, can we totally ignore list_a and just assume each key in list_b has a match in list_a when we split on '.'? What should we do if key has no matches? multiple matches? – smci Sep 18 '19 at 22:54

{k: k.split('.', 1)[0] for k in list_b}

p.s. don't call your variable dict_. Name it according to its application function - animals, or whatever.