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.

Thanks in advance!

  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Graipher Sep 18 '19 at 17:30
  • \$\begingroup\$ 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... \$\endgroup\$ – smci Sep 18 '19 at 22:52
  • \$\begingroup\$ 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? \$\endgroup\$ – smci Sep 18 '19 at 22:54

You don't even need to use the second list. You can do a dict comprehension:

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

This assumes that the data are all structured as you've shown, with a prefix, a dot and a number.

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

| improve this answer | |
  • \$\begingroup\$ The data is indeed structured as shown. This is much more readable! \$\endgroup\$ – Andrew Hamel Sep 18 '19 at 17:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.