简体   繁体   中英

how to convert two unsorted lists into a dictionary in a pythonic way?

I need to convert two unsorted lists into a dictionary. For example, I have a full name list:

full_name = ['taylor/swift', 'lady/gaga', 'leborn/james', 'james/harden']

And I have a last name list:

last_name = ['harden', 'james', 'swift', 'smith']

I need to convert these two lists into a dictionary:

{'harden':'james/harden', 'james':'leborn/james', 'swift':'taylor/swift'}

Notice that length of two lists are not equal. What's more, some of elements in last name list cannot be found in full_name list.I wrote a python script to complete the task.

def index_match(full_index, last_index):
    last_valid = [s for s in last_index if any(s in xs for xs in full_index)]
    matcher = []
    for s in last_valid:
        for xs in full_index:
            if s in xs:
                matcher.append(xs)
                break
    return dict(zip(last_valid, matcher))
    
matcher = index_match(full_name, last_name)

for item in matcher.items():
    print(item)

And it works fine. But when the length of list increases, the program runs slowly. I tried to use dictionary comprehension to solve the problem, but I got syntax errors. What should i do to write the program in a more pythonic way to improve the speed?

full_name = ['taylor/swift', 'lady/gaga', 'leborn/james', 'james/harden']
last_name = ['harden', 'james', 'swift', 'smith']

out = {l:f for l in last_name for f in full_name if f.split("/")[1] == l}
print(out)

Output:

{'harden': 'james/harden', 'james': 'leborn/james', 'swift': 'taylor/swift'}

Use dictionary comprehension for a faster method:

full_name = ['taylor/swift', 'lady/gaga', 'leborn/james', 'james/harden']
last_name = ['harden', 'james', 'swift', 'smith']
last_name_to_full_name = {f.split(r'/')[1]: f for f in full_name}
last_name_to_full_name = {L: last_name_to_full_name[L] for L in last_name
                          if L in last_name_to_full_name}
print(last_name_to_full_name)
# {'harden': 'james/harden', 'james': 'leborn/james', 'swift': 'taylor/swift'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM