Sort not identical lists Python

I have two lists.

One list contains only codes e.g.:

b3b
3cd
6f6
4d8
96b
00a
774
eb3
607
7e5

The other list contains code with names e.g.

b3b:John
607:Eric
7e5:Jarrold

But the list is not compleet yet.

What I want as output, because the other cannot be removed and has to be in the right order, e.g.

b3b:John
3cd
6f6
4d8
96b
00a
774
eb3
607:Eric
7e5:Jarrold

Already have this code but it only returns True or False but that's not what I want.

list1 = [line.strip() for line in open('list1')]
list2 = [line.strip() for line in open('list2')]

comp = [i[:3] for i in list2]

for i in list1:
    print(i, i in list2)

Maybe anyone who can help me with this?

Answers


You should use a dictionary mapping keys to names instead of a list as the second data structure:

with open("list1") as f:
    keys = [line.strip() for line in f]
with open("list2") as f:
    names = dict(line.strip().split(":", 1) for line in f)

Now you can efficiently implement your loop:

for k in keys:
    print(k, names.get(k, ""))

Performing a linear search in list2 for every entry of list1 would be rather inefficient. Apart from the better performance, a dictionary is also a better model of the meaning of your data.


Need Your Help

Multiple template types

c++ templates

Is it possible to have multiple template types in C++?

Capture HTTPS handshake

security ssl https fiddler wireshark

I want to understand how HTTPS works, so at beginning I would like to capture all request which are exchanged by client and server (handshake, sent certificate etc)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.